aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/source
diff options
context:
space:
mode:
authorCassioMarques <cassiommc@gmail.com>2008-12-28 21:27:31 -0200
committerCassioMarques <cassiommc@gmail.com>2008-12-28 21:27:31 -0200
commit495c7109fee3f61a227c0ef8c820bd9bc009c2d8 (patch)
treee6648ae03567b269d8e8612bf6d168005f49ffed /railties/doc/guides/source
parentd6c2285e31cbc7150cf99ff3a537eddbdb50fb29 (diff)
downloadrails-495c7109fee3f61a227c0ef8c820bd9bc009c2d8.tar.gz
rails-495c7109fee3f61a227c0ef8c820bd9bc009c2d8.tar.bz2
rails-495c7109fee3f61a227c0ef8c820bd9bc009c2d8.zip
New content for the AR Validations and Callbacks guide: Added a section about using error messages in view templates, added text about custom validation helpers
Diffstat (limited to 'railties/doc/guides/source')
-rw-r--r--railties/doc/guides/source/activerecord_validations_callbacks.txt116
1 files changed, 115 insertions, 1 deletions
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
index e0bb534d0b..9acda5f42e 100644
--- a/railties/doc/guides/source/activerecord_validations_callbacks.txt
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -415,7 +415,34 @@ class Invoice < ActiveRecord::Base
end
------------------------------------------------------------------
-== Using the +errors+ collection
+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:
+
+[source, ruby]
+------------------------------------------------------------------
+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 => "Formato de email incorreto"
+ 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:
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_email_format_of :email_address
+end
+------------------------------------------------------------------
+
+== 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.
@@ -498,6 +525,93 @@ p.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
------------------------------------------------------------------
+== 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.
+
+[source, ruby]
+------------------------------------------------------------------
+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 %>
+------------------------------------------------------------------
+
+image::images/error_messages.png[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
+
+image::images/customized_error_messages.png[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.
+
+=== 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.
+
+[source, ruby]
+------------------------------------------------------------------
+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:
+
+image::images/validation_error_messages.png[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.
+
== 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.