From 006a640fc4dff5a7a0ea471fb904dd27068b6545 Mon Sep 17 00:00:00 2001 From: CassioMarques Date: Sun, 28 Dec 2008 21:49:33 -0200 Subject: Fixed error message that was written in portuguese instead of english... --- .../html/activerecord_validations_callbacks.html | 189 +++++++++++++++++++-- 1 file changed, 171 insertions(+), 18 deletions(-) (limited to 'railties/doc/guides/html/activerecord_validations_callbacks.html') diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index e1d8e5be4f..a5356f3daf 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -267,7 +267,15 @@ ul#navMain { Writing your own validation methods
  • - Using the errors collection + Manipulating the errors collection +
  • +
  • + Using the errors collection in your view templates +
  • Callbacks @@ -781,8 +789,35 @@ http://www.gnu.org/software/src-highlite --> discount <= total_value end end +

    You can even create your own validation helpers and reuse them in several different models. Here is an example where we create a custom validation helper to validate the format of fields that represent email addresses:

    +
    +
    +
    module ActiveRecord
    +  module Validations
    +    module ClassMethods
    +      def validates_email_format_of(value)
    +        validates_format_of value,
    +          :with => /\A[\w\._%-]+@[\w\.-]+\.[a-zA-Z]{2,4}\z/,
    +          :if => Proc.new { |u| !u.email.blank? },
    +          :message => "Invalid format for email address"
    +      end
    +    end
    +  end
    +end
    +

    The recipe is simple: just create a new validation method inside the ActiveRecord::Validations::ClassMethods module. You can put this code in a file inside your application’s lib folder, and then requiring it from your environment.rb or any other file inside config/initializers. You can use this helper like this:

    +
    +
    +
    class Person < ActiveRecord::Base
    +  validates_email_format_of :email_address
    +end
    -

    7. Using the errors collection

    +

    7. Manipulating the errors collection

    You can do more than just call valid? upon your objects based on the existance of the errors collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object’s state.

      @@ -895,12 +930,130 @@ p.save .errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
    -

    8. Callbacks

    +

    8. Using the errors collection in your view templates

    +
    +

    Rails provides built-in helpers to display the error messages of your models in your view templates. It may be useful to display those messages when you’re trying to create or edit a record and validation fails. If you’re using the form_for helper to create a form, you can use it to call the error_messages method, which creates a div element containing all the error messages for the model associated with the form. Here is a simple example, using a Product model and the view template generated with the scaffold script.

    +
    +
    +
    class Product < ActiveRecord::Base
    +  validates_presence_of :description, :value
    +  validates_numericality_of :value, :allow_nil => true
    +end
    +
    +
    +
    <% form_for(@product) do |f| %>
    +  <%= f.error_messages %>
    +  <p>
    +    <%= f.label :description %><br />
    +    <%= f.text_field :description %>
    +  </p>
    +  <p>
    +    <%= f.label :value %><br />
    +    <%= f.text_field :value %>
    +  </p>
    +  <p>
    +    <%= f.submit "Create" %>
    +  </p>
    +<% end %>
    +
    +
    +
    +Error messages +
    +
    +

    You can also use the error_messages_for helper to display the error messages of a model assigned to a view template. It’s very similar to the previous example and will achieve exactly the same result.

    +
    +
    +
    <%= error_messages_for :product %>
    +
    +

    The displayed text for each error message will always be formed by the capitalized name of the attribute that holds the error, followed by the error message itself.

    +

    Both the form.error_messages and the error_messages_for helpers accept options that let you customize the div element that holds the messages, changing the header text, the message below the header text and the tag used for the element that defines the header.

    +
    +
    +
    <%= f.error_messages :header_message => "Invalid product!",
    +  :message => "You'll need to fix the following fields:",
    +  :header_tag => :h3 %>
    +
    +

    Which results in the following content

    +
    +
    +Customized error messages +
    +
    +

    If you pass nil to any of these options, it will get rid of the respective section of the div.

    +

    It’s also possible to change the CSS classes used by the error_messages helper. These classes are automatically defined at the scaffold.css file, generated by the scaffold script. If you’re not using scaffolding, you can still define those CSS classes at your CSS files. Here is a list of the default CSS classes.

    +
      +
    • +

      +.fieldWithErrors - Style for the form fields with errors. +

      +
    • +
    • +

      +#errorExplanation - Style for the div element with the error messages. +

      +
    • +
    • +

      +#errorExplanation h2 - Style for the header of the div element. +

      +
    • +
    • +

      +#errorExplanation p - Style for the paragraph that holds the message that appears right below the header of the div element. +

      +
    • +
    • +

      +#errorExplanation ul li - Style for the list of error messages. +

      +
    • +
    +

    8.1. Changing the way form fields with errors are displayed

    +

    By default, form fields with errors are displayed enclosed by a div element with the fieldWithErrors CSS class. However, we can write some Ruby code to override the way Rails treats those fields by default. Here is a simple example where we change the Rails behaviour to always display the error messages in front of each of the form fields with errors. The error messages will be enclosed by a span element with a validation-error CSS class.

    +
    +
    +
    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
    +  if instance.error_message.kind_of?(Array)
    +    %(#{html_tag}<span class='validation-error'>&nbsp;
    +      #{instance.error_message.join(',')}</span>)
    +  else
    +    %(#{html_tag}<span class='validation-error'>&nbsp;
    +      #{instance.error_message}</span>)
    +  end
    +end
    +

    This will result in something like the following content:

    +
    +
    +Validation error messages +
    +
    +

    The way form fields with errors are treated is defined by the ActionView::Base.field_error_proc Ruby Proc. This Proc receives two parameters:

    +
      +
    • +

      +A string with the HTML tag +

      +
    • +
    • +

      +An object of the ActionView::Helpers::InstanceTag class. +

      +
    • +
    +
    +

    9. Callbacks

    Callbacks are methods that get called at certain moments of an object’s lifecycle. With callbacks it’s possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database.

    -

    8.1. Callbacks registration

    +

    9.1. Callbacks registration

    In order to use the available callbacks, you need to registrate them. There are two ways of doing that.

    -

    8.2. Registering callbacks by overriding the callback methods

    +

    9.2. Registering callbacks by overriding the callback methods

    You can specify the callback method directly, by overriding it. Let’s see how it works using the before_validation callback, which will surprisingly run right before any validation is done.

    end end end
    -

    8.3. Registering callbacks by using macro-style class methods

    +

    9.3. Registering callbacks by using macro-style class methods

    The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that:

    end

    You can declare as many callbacks as you want inside your callback classes.

    -

    12. Observers

    +

    13. Observers

    Active Record callbacks are a powerful feature, but they can pollute your model implementation with code that’s not directly related to the model’s purpose. In object-oriented software, it’s always a good idea to design your classes with a single responsability in the whole system. For example, it wouldn’t make much sense to have a User model with a method that writes data about a login attempt to a log file. Whenever you’re using callbacks to write code that’s not directly related to your model class purposes, it may be a good moment to create an Observer.

    An Active Record Observer is an object that links itself to a model and register it’s methods for callbacks. Your model’s implementation remain clean, while you can reuse the code in the Observer to add behaviuor to more than one model class. Ok, you may say that we can also do that using callback classes, but it would still force us to add code to our model’s implementation.

    @@ -1155,7 +1308,7 @@ http://www.gnu.org/software/src-highlite -->
    class Auditor < ActiveRecord::Observer
       observe User, Registration, Invoice
     end
    -

    12.1. Registering observers

    +

    13.1. Registering observers

    If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register them somewhere. The usual place to do that is in our application’s config/environment.rb file. In this file there is a commented out line where we can define the observers that our application should load at start-up.

    config.active_record.observers = :registration_observer, :auditor

    You can uncomment the line with config.active_record.observers and change the symbols for the name of the observers that should be registered.

    It’s also possible to register callbacks in any of the files living at config/environments/, if you want an observer to work only in a specific environment. There is not a config.active_record.observers line at any of those files, but you can simply add it.

    -

    12.2. Where to put the observers' source files

    +

    13.2. Where to put the observers' source files

    By convention, you should always save your observers' source files inside app/models.

    -

    13. Changelog

    +

    14. Changelog

    -- cgit v1.2.3