From 5a22f05522d4b624463da174576f3663ea2872ac Mon Sep 17 00:00:00 2001 From: Alberto Perdomo Date: Thu, 28 Jul 2011 00:51:14 +0100 Subject: Association and Callbacks guide: Added section on shortcut syntax 'validates'. --- .../active_record_validations_callbacks.textile | 55 ++++++++++++++++++++++ 1 file changed, 55 insertions(+) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index ce0b5416de..e2ec874190 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -612,6 +612,61 @@ class Movie < ActiveRecord::Base end +h3. Shortcut helper + +There is a special method +validates+ that is a shortcut to all default validators and any custom validator classes ending in 'Validator'. Note that Rails default validators can be overridden inside specific classes by creating custom validator classes in their place such as +PresenceValidator+. + +h4. Multiple validations for a single attribue + +In cases where you want multiple validations for a single attribute you can do it with a one-liner. + + +class User < ActiveRecord::Base + validates :password, :presence => true, :confirmation => true, :length => { :minimum => 6 } +end + + +h4. Combining standard validations with custom validators + +You can also combine standard validations with your own custom validators. + + +class EmailValidator < ActiveModel::EachValidator + def validate_each(record, attribute, value) + record.errors[attribute] << (options[:message] || "is not an email") unless + value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i + end +end + +class Person + include ActiveModel::Validations + attr_accessor :name, :email + + validates :name, :presence => true, :uniqueness => true, :length => { :maximum => 100 } + validates :email, :presence => true, :email => true +end + + +h4. Validating multiple attributes with the same criteria + +If you have a case where you want to apply the same validations to multiple attributes you can do that as well. + + +class BlogPost < ActiveRecord::Base + validates :title, :body, :presence => true +end + + +h4. Using the standard options + +The shortcut syntax is also compatible with the standard options +:allow_nil+, +:allow_blank+, etc. as well as the conditional options +:if+ and +unless+. + + +class User < ActiveRecord::Base + validates :password, :presence => { :if => :password_required? }, :confirmation => true +end + + h3. Working with Validation Errors In addition to the +valid?+ and +invalid?+ methods covered earlier, Rails provides a number of methods for working with the +errors+ collection and inquiring about the validity of objects. -- cgit v1.2.3 From 225a2482c19fa3a1acdc05371a44b090c6cb4d7c Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 30 Jul 2011 23:50:31 +0530 Subject: remove some parts of the section on shortcut helpers, document custom validators --- .../active_record_validations_callbacks.textile | 104 +++++++++------------ 1 file changed, 45 insertions(+), 59 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index e2ec874190..5789d36c6d 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -569,101 +569,87 @@ end All validations inside of +with_options+ block will have automatically passed the condition +:if => :is_admin?+ -h3. Creating Custom Validation Methods +h3. Performing Custom Validations -When the built-in validation helpers are not enough for your needs, you can write your own validation methods. +When the built-in validation helpers are not enough for your needs, you can write your own validators or validation methods as you prefer. -Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names. +h4. Custom Validators -You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered. +Custom validators are classes that extend ActiveModel::Validator. These classes must implement a +validate+ method which takes a record as an argument and performs the validation on it. The custom validator is called using the +validates_with+ method. -class Invoice < ActiveRecord::Base - validate :expiration_date_cannot_be_in_the_past, - :discount_cannot_be_greater_than_total_value - - def expiration_date_cannot_be_in_the_past - errors.add(:expiration_date, "can't be in the past") if - !expiration_date.blank? and expiration_date < Date.today +class MyValidator < ActiveModel::Validator + def validate(record) + if record.name.starts_with? 'X' + record.errors[:name] << 'Need a name starting with X please!' + end end +end - def discount_cannot_be_greater_than_total_value - errors.add(:discount, "can't be greater than total value") if - discount > total_value - end +class Person + include ActiveModel::Validations + validates_with MyValidator end -You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices: +The easiest way to add custom validators for validating individual attributes is with the convenient ActiveModel::EachValidator. In this case, the custom validator class must implement a +validate_each+ method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance. -ActiveRecord::Base.class_eval do - def self.validates_as_choice(attr_name, n, options={}) - validates attr_name, :inclusion => { {:in => 1..n}.merge(options) } +class EmailValidator < ActiveModel::EachValidator + def validate_each(record, attribute, value) + unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i + record.errors[attribute] << (options[:message] || "is not an email") + end end end - - -Simply reopen +ActiveRecord::Base+ and define a class method like that. You'd typically put this code somewhere in +config/initializers+. You can use this helper like this: - -class Movie < ActiveRecord::Base - validates_as_choice :rating, 5 +class Person < ActiveRecord::Base + validates :email, :presence => true, :email => true end -h3. Shortcut helper +As shown in the example, you can also combine standard validations with your own custom validators. -There is a special method +validates+ that is a shortcut to all default validators and any custom validator classes ending in 'Validator'. Note that Rails default validators can be overridden inside specific classes by creating custom validator classes in their place such as +PresenceValidator+. +h4. Custom Methods -h4. Multiple validations for a single attribue +You can also create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names. -In cases where you want multiple validations for a single attribute you can do it with a one-liner. +You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered. -class User < ActiveRecord::Base - validates :password, :presence => true, :confirmation => true, :length => { :minimum => 6 } -end - - -h4. Combining standard validations with custom validators - -You can also combine standard validations with your own custom validators. +class Invoice < ActiveRecord::Base + validate :expiration_date_cannot_be_in_the_past, + :discount_cannot_be_greater_than_total_value - -class EmailValidator < ActiveModel::EachValidator - def validate_each(record, attribute, value) - record.errors[attribute] << (options[:message] || "is not an email") unless - value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i + def expiration_date_cannot_be_in_the_past + if !expiration_date.blank? and expiration_date < Date.today + errors.add(:expiration_date, "can't be in the past") + end end -end - -class Person - include ActiveModel::Validations - attr_accessor :name, :email - validates :name, :presence => true, :uniqueness => true, :length => { :maximum => 100 } - validates :email, :presence => true, :email => true + def discount_cannot_be_greater_than_total_value + if discount > total_value + errors.add(:discount, "can't be greater than total value") + end + end end -h4. Validating multiple attributes with the same criteria - -If you have a case where you want to apply the same validations to multiple attributes you can do that as well. +You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices: -class BlogPost < ActiveRecord::Base - validates :title, :body, :presence => true +ActiveRecord::Base.class_eval do + def self.validates_as_choice(attr_name, n, options={}) + validates attr_name, :inclusion => { {:in => 1..n}.merge(options) } + end end -h4. Using the standard options - -The shortcut syntax is also compatible with the standard options +:allow_nil+, +:allow_blank+, etc. as well as the conditional options +:if+ and +unless+. +Simply reopen +ActiveRecord::Base+ and define a class method like that. You'd typically put this code somewhere in +config/initializers+. You can use this helper like this: -class User < ActiveRecord::Base - validates :password, :presence => { :if => :password_required? }, :confirmation => true +class Movie < ActiveRecord::Base + validates_as_choice :rating, 5 end -- cgit v1.2.3 From ad9e52f156575f28949837a3dd0fa433fa824d57 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 30 Jul 2011 23:53:11 +0530 Subject: prefer to use if..end unless the condition is simple/compact --- .../guides/source/active_record_validations_callbacks.textile | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 5789d36c6d..977e736d25 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -1143,8 +1143,9 @@ Here's an example where we create a class with an +after_destroy+ callback for a class PictureFileCallbacks def after_destroy(picture_file) - File.delete(picture_file.filepath) - if File.exists?(picture_file.filepath) + if File.exists?(picture_file.filepath) + File.delete(picture_file.filepath) + end end end @@ -1162,8 +1163,9 @@ Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we class PictureFileCallbacks def self.after_destroy(picture_file) - File.delete(picture_file.filepath) - if File.exists?(picture_file.filepath) + if File.exists?(picture_file.filepath) + File.delete(picture_file.filepath) + end end end -- cgit v1.2.3 From c5f97b5063d1d60341f9e984f29a3b9812fb4c7e Mon Sep 17 00:00:00 2001 From: Jeff Dutil Date: Tue, 16 Aug 2011 13:12:07 -0400 Subject: Fix formatting of active_record_validations_callbacks.textile so guide will render properly at http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#displaying-validation-errors-in-the-view --- railties/guides/source/active_record_validations_callbacks.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 977e736d25..aba3224ba7 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -751,8 +751,6 @@ class Person < ActiveRecord::Base end - - h4. +errors.clear+ The +clear+ method is used when you intentionally want to clear all the messages in the +errors+ collection. Of course, calling +errors.clear+ upon an invalid object won't actually make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the +errors+ collection will be filled again. @@ -799,6 +797,7 @@ h3. Displaying Validation Errors in the View Rails maintains an official plugin that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem. h4. Installing as a plugin + $ rails plugin install git://github.com/joelmoss/dynamic_form.git @@ -806,6 +805,7 @@ $ rails plugin install git://github.com/joelmoss/dynamic_form.git h4. Installing as a Gem Add this line in your Gemfile: + gem "dynamic_form" -- cgit v1.2.3 From a5e925c1d35ff10a22a98841f6a02925d4263947 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Wed, 24 Aug 2011 10:25:29 +0300 Subject: Add strict validation example to guides --- railties/guides/source/active_record_validations_callbacks.textile | 1 + 1 file changed, 1 insertion(+) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index aba3224ba7..18fc77c660 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -1270,6 +1270,7 @@ The +after_commit+ and +after_rollback+ callbacks are guaranteed to be called fo h3. Changelog +* August 24, 2011: Add strict validation usage example. "Bogdan Gusiev":http://gusiev.com * February 17, 2011: Add description of transaction callbacks. * July 20, 2010: Fixed typos and rephrased some paragraphs for clarity. "Jaime Iniesta":http://jaimeiniesta.com * May 24, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com -- cgit v1.2.3 From f2f05da06e48b5b4996380af33b59733048032f2 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Thu, 25 Aug 2011 19:37:11 +0300 Subject: Moved strict validation changelog entry to right place --- railties/guides/source/active_record_validations_callbacks.textile | 1 - 1 file changed, 1 deletion(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 18fc77c660..aba3224ba7 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -1270,7 +1270,6 @@ The +after_commit+ and +after_rollback+ callbacks are guaranteed to be called fo h3. Changelog -* August 24, 2011: Add strict validation usage example. "Bogdan Gusiev":http://gusiev.com * February 17, 2011: Add description of transaction callbacks. * July 20, 2010: Fixed typos and rephrased some paragraphs for clarity. "Jaime Iniesta":http://jaimeiniesta.com * May 24, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com -- cgit v1.2.3 From 9980f46ca2d250d1d3e2fac84c5dc9ca6cbab1ea Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 15 Sep 2011 00:13:29 +0530 Subject: No more changelogs inside guides --- .../guides/source/active_record_validations_callbacks.textile | 11 ----------- 1 file changed, 11 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index aba3224ba7..20f5e52891 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -1267,14 +1267,3 @@ end The +after_commit+ and +after_rollback+ callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback. - -h3. Changelog - -* February 17, 2011: Add description of transaction callbacks. -* July 20, 2010: Fixed typos and rephrased some paragraphs for clarity. "Jaime Iniesta":http://jaimeiniesta.com -* May 24, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com -* May 15, 2010: Validation Errors section updated by "Emili Parreño":http://www.eparreno.com -* March 7, 2009: Callbacks revision by Trevor Turk -* February 10, 2009: Observers revision by Trevor Turk -* February 5, 2009: Initial revision by Trevor Turk -* January 9, 2009: Initial version by "Cássio Marques":credits.html#cmarques -- cgit v1.2.3 From 27f1320fde03279c575693f504897f1a6171bc59 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Fri, 16 Sep 2011 22:12:41 +0530 Subject: Fixing incorrect notextile tags --- railties/guides/source/active_record_validations_callbacks.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 20f5e52891..5c3aae2955 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -328,7 +328,7 @@ This helper validates that your attributes have only numeric values. By default, If you set +:only_integer+ to +true+, then it will use the -/\A[+-]?\d+\Z/ +/\A[-]?\d\Z/ regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using +Float+. @@ -597,7 +597,7 @@ The easiest way to add custom validators for validating individual attributes is class EmailValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) - unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i + unless value =~ /\A([^@\s])@((?:[-a-z0-9]\.)+[a-z]{2,})\z/i record.errors[attribute] << (options[:message] || "is not an email") end end -- cgit v1.2.3 From 547f4af2ca34058e591f8c2912d47c562a0935ef Mon Sep 17 00:00:00 2001 From: Manuel Menezes de Sequeira Date: Mon, 3 Oct 2011 18:03:35 +0100 Subject: Several small corrections and clarifications to the Active Record Validations and Callbacks guide. --- .../active_record_validations_callbacks.textile | 34 ++++++++++++---------- 1 file changed, 18 insertions(+), 16 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 5c3aae2955..262ea42898 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -28,7 +28,7 @@ h4. Why Use Validations? Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. -There are several ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations, and model-level validations. +There are several ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations, and model-level validations: * Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise. * Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site. @@ -94,7 +94,7 @@ Note that +save+ also has the ability to skip validations if passed +:validate = h4. +valid?+ and +invalid?+ -To verify whether or not an object is valid, Rails uses the +valid?+ method. You can also use this method on your own. +valid?+ triggers your validations and returns true if no errors were added to the object, and false otherwise. +To verify whether or not an object is valid, Rails uses the +valid?+ method. You can also use this method on your own. +valid?+ triggers your validations and returns true if no errors were found in the object, and false otherwise. class Person < ActiveRecord::Base @@ -105,7 +105,7 @@ Person.create(:name => "John Doe").valid? # => true Person.create(:name => nil).valid? # => false -When Active Record is performing validations, any errors found can be accessed through the +errors+ instance method. By definition an object is valid if this collection is empty after running validations. +After Active Record performing validations, any errors found can be accessed through the +errors+ instance method, which returns a collection of errors. By definition an object is valid if this collection is empty after running validations. Note that an object instantiated with +new+ will not report errors even if it's technically invalid, because validations are not run when using +new+. @@ -139,7 +139,7 @@ end => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank -+invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations and returns true if any errors were added to the object, and false otherwise. ++invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations, returning true if any errors were found in the object, and false otherwise. h4(#validations_overview-errors). +errors[]+ @@ -160,7 +160,7 @@ We'll cover validation errors in greater depth in the "Working with Validation E h3. Validation Helpers -Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated. +Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the attribute being validated. Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes. @@ -428,6 +428,8 @@ class GoodnessValidator < ActiveModel::Validator end +NOTE: Errors added to +record.errors[:base]+ relate to the state of the record as a whole, and not to a specific attribute. + The +validates_with+ helper takes a class, or a list of classes to use for validation. There is no default error message for +validates_with+. You must manually add errors to the record's errors collection in the validator class. To implement the validate method, you must have a +record+ parameter defined, which is the record to be validated. @@ -454,13 +456,13 @@ This helper validates attributes against a block. It doesn't have a predefined v class Person < ActiveRecord::Base - validates_each :name, :surname do |model, attr, value| - model.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/ + validates_each :name, :surname do |record, attr, value| + record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/ end end -The block receives the model, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you can add an error message to the model, therefore making it invalid. +The block receives the record, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you should add an error message to the model, therefore making it invalid. h3. Common Validation Options @@ -580,7 +582,7 @@ Custom validators are classes that extend ActiveModel::Validator. These class MyValidator < ActiveModel::Validator def validate(record) - if record.name.starts_with? 'X' + unless record.name.starts_with? 'X' record.errors[:name] << 'Need a name starting with X please!' end end @@ -661,7 +663,7 @@ The following is a list of the most commonly used methods. Please refer to the + h4(#working_with_validation_errors-errors). +errors+ -Returns an OrderedHash with all errors. Each key is the attribute name and the value is an array of strings with all errors. +Returns an instance of the class +ActiveModel::Errors+ (which behaves like an ordered hash) containing all errors. Each key is the attribute name and the value is an array of strings with all errors. class Person < ActiveRecord::Base @@ -741,7 +743,7 @@ Another way to do this is using +[]=+ setter h4. +errors[:base]+ -You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since +errors[:base]+ is an array, you can simply add a string to the array and uses it as the error message. +You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since +errors[:base]+ is an array, you can simply add a string to it and it will be used as an error message. class Person < ActiveRecord::Base @@ -785,7 +787,7 @@ end person = Person.new person.valid? # => false -person.errors.size # => 3 +person.errors.size # => 2 person = Person.new(:name => "Andrea", :email => "andrea@example.com") person.valid? # => true @@ -871,10 +873,10 @@ h4. Customizing the Error Messages CSS The selectors to customize the style of error messages are: * +.field_with_errors+ - Style for the form fields and labels 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 items with individual error messages. +* +#error_explanation+ - Style for the +div+ element with the error messages. +* +#error_explanation h2+ - Style for the header of the +div+ element. +* +#error_explanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element. +* +#error_explanation ul li+ - Style for the list items with individual error messages. Scaffolding for example generates +app/assets/stylesheets/scaffold.css.scss+, which later compiles to +app/assets/stylesheets/scaffold.css+ and defines the red-based style you saw above. -- cgit v1.2.3 From bb4edc8edf5dd10b0c83b8920d76751fd93ffd7e Mon Sep 17 00:00:00 2001 From: Manuel Menezes de Sequeira Date: Tue, 4 Oct 2011 16:13:16 +0100 Subject: More corrections and clarifications to the Active Record Validations and Callbacks guide. --- .../active_record_validations_callbacks.textile | 91 ++++++++++++---------- 1 file changed, 52 insertions(+), 39 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 262ea42898..6c6f29be32 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -796,7 +796,7 @@ person.errors.size # => 0 h3. Displaying Validation Errors in the View -Rails maintains an official plugin that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem. +Rails maintains an official plugin, DynamicForm, that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem. h4. Installing as a plugin @@ -812,7 +812,7 @@ Add this line in your Gemfile: gem "dynamic_form" -Now you will have access to these two methods in your view templates. +Now you will have access to the two help methods +error_messages+ and +error_messages_for+ in your view templates. h4. +error_messages+ and +error_messages_for+ @@ -842,11 +842,13 @@ end <% end %> -To get the idea, if you submit the form with empty fields you typically get this back, though styles are indeed missing by default: +If you submit the form with empty fields, the result will be similar to the one shown below: !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. +NOTE: The appearance of the generated HTML will be different from the one shown, unless you have used scaffolding. See "Customizing the Error Messages CSS":#customizing-error-messages-css. + +You can also use the +error_messages_for+ helper to display the error messages of a model assigned to a view template. It is very similar to the previous example and will achieve exactly the same result. <%= error_messages_for :product %> @@ -854,7 +856,7 @@ You can also use the +error_messages_for+ helper to display the error messages o 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. +Both the +form.error_messages+ and the +error_messages_for+ helpers accept options that let you customize the +div+ element that holds the messages, change the header text, change the message below the header, and specify the tag used for the header element. For example, <%= f.error_messages :header_message => "Invalid product!", @@ -862,23 +864,23 @@ Both the +form.error_messages+ and the +error_messages_for+ helpers accept optio :header_tag => :h3 %> -Which results in the following content: +results in: !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+. +If you pass +nil+ in any of these options, the corresponding section of the +div+ will be discarded. -h4. Customizing the Error Messages CSS +h4(#customizing-error-messages-css). Customizing the Error Messages CSS -The selectors to customize the style of error messages are: +The selectors used to customize the style of error messages are: * +.field_with_errors+ - Style for the form fields and labels with errors. * +#error_explanation+ - Style for the +div+ element with the error messages. * +#error_explanation h2+ - Style for the header of the +div+ element. -* +#error_explanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element. +* +#error_explanation p+ - Style for the paragraph holding the message that appears right below the header of the +div+ element. * +#error_explanation ul li+ - Style for the list items with individual error messages. -Scaffolding for example generates +app/assets/stylesheets/scaffold.css.scss+, which later compiles to +app/assets/stylesheets/scaffold.css+ and defines the red-based style you saw above. +If scaffolding was used, file +app/assets/stylesheets/scaffold.css.scss+ (which later compiles to +app/assets/stylesheets/scaffold.css+), will have been generated automatically. This file defines the red-based styles you saw in the examples above. The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers. @@ -891,7 +893,7 @@ The way form fields with errors are treated is defined by +ActionView::Base.fiel * A string with the HTML tag * An instance of +ActionView::Helpers::InstanceTag+. -Here is a simple example where we change the Rails behavior 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. There will be no +div+ element enclosing the +input+ element, so we get rid of that red border around the text field. You can use the +validation-error+ CSS class to style it anyway you want. +Below is a simple example where we change the Rails behavior to always display the error messages in front of each of the form fields in error. The error messages will be enclosed by a +span+ element with a +validation-error+ CSS class. There will be no +div+ element enclosing the +input+ element, so we get rid of that red border around the text field. You can use the +validation-error+ CSS class to style it anyway you want. ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| @@ -905,17 +907,17 @@ ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| end -This will result in something like the following: +The result look like the following: !images/validation_error_messages.png(Validation error messages)! h3. Callbacks Overview -Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database. +Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database. h4. Callback Registration -In order to use the available callbacks, you need to register them. You can do that by implementing them as ordinary methods, and then using a macro-style class method to register them as callbacks. +In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks: class User < ActiveRecord::Base @@ -932,7 +934,7 @@ class User < ActiveRecord::Base end -The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in just one line. +The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in a single line: class User < ActiveRecord::Base @@ -944,7 +946,7 @@ class User < ActiveRecord::Base end -It's considered good practice to declare callback methods as being protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation. +It is considered good practice to declare callback methods as protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation. h3. Available Callbacks @@ -984,7 +986,7 @@ The +after_initialize+ callback will be called whenever an Active Record object The +after_find+ callback will be called whenever Active Record loads a record from the database. +after_find+ is called before +after_initialize+ if both are defined. -The +after_initialize+ and +after_find+ callbacks are a bit different from the others. They have no +before_*+ counterparts, and the only way to register them is by defining them as regular methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behavior is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries. +The +after_initialize+ and +after_find+ callbacks are a bit different from the others. They have no +before_*+ counterparts, and they are registered simply by defining them as regular methods with predefined names. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behavior is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, which would otherwise significantly slow down the queries. class User < ActiveRecord::Base @@ -1041,7 +1043,7 @@ The +after_initialize+ callback is triggered every time a new object of the clas h3. Skipping Callbacks -Just as with validations, it's also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data. +Just as with validations, it is also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data. * +decrement+ * +decrement_counter+ @@ -1060,13 +1062,13 @@ h3. Halting Execution As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed. -The whole callback chain is wrapped in a transaction. If any before callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued; after callbacks can only accomplish that by raising an exception. +The whole callback chain is wrapped in a transaction. If any before callback method returns exactly +false+ or raises an exception, the execution chain gets halted and a ROLLBACK is issued; after callbacks can only accomplish that by raising an exception. -WARNING. Raising an arbitrary exception may break code that expects +save+ and friends not to fail like that. The +ActiveRecord::Rollback+ exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised. +WARNING. Raising an arbitrary exception may break code that expects +save+ and its friends not to fail like that. The +ActiveRecord::Rollback+ exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised. h3. Relational Callbacks -Callbacks work through model relationships, and can even be defined by them. Let's take an example where a user has many posts. In our example, a user's posts should be destroyed if the user is destroyed. So, we'll add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model. +Callbacks work through model relationships, and can even be defined by them. Suppose an example where a user has many posts. A user's posts should be destroyed if the user is destroyed. Let's add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model: class User < ActiveRecord::Base @@ -1092,11 +1094,11 @@ Post destroyed h3. Conditional Callbacks -Like in validations, we can also make our callbacks conditional, calling them only when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a +Proc+. You may use the +:if+ option when you want to specify when the callback *should* get called. If you want to specify when the callback *should not* be called, then you may use the +:unless+ option. +As with validations, we can also make the calling of a callback method conditional on the satisfaction of a given predicate. We can do this using the +:if+ and +:unless+ options, which can take a symbol, a string or a +Proc+. You may use the +:if+ option when you want to specify under which conditions the callback *should* be called. If you want to specify the conditions under which the callback *should not* be called, then you may use the +:unless+ option. -h4. Using +:if+ and +:unless+ with a Symbol +h4. Using +:if+ and +:unless+ with a +Symbol+ -You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before the callback. When using the +:if+ option, the callback won't be executed if the method returns false; when using the +:unless+ option, the callback won't be executed if the method returns true. This is the most common option. Using this form of registration it's also possible to register several different methods that should be called to check if the callback should be executed. +You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the +:if+ option, the callback won't be executed if the predicate method returns false; when using the +:unless+ option, the callback won't be executed if the predicate method returns true. This is the most common option. Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed. class Order < ActiveRecord::Base @@ -1106,7 +1108,7 @@ end h4. Using +:if+ and +:unless+ with a String -You can also use a string that will be evaluated using +eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition. +You can also use a string that will be evaluated using +eval+ and hence needs to contain valid Ruby code. You should use this option only when the string represents a really short condition: class Order < ActiveRecord::Base @@ -1114,9 +1116,9 @@ class Order < ActiveRecord::Base end -h4. Using +:if+ and +:unless+ with a Proc +h4. Using +:if+ and +:unless+ with a +Proc+ -Finally, it's possible to associate +:if+ and +:unless+ with a +Proc+ object. This option is best suited when writing short validation methods, usually one-liners. +Finally, it is possible to associate +:if+ and +:unless+ with a +Proc+ object. This option is best suited when writing short validation methods, usually one-liners: class Order < ActiveRecord::Base @@ -1127,7 +1129,7 @@ end h4. Multiple Conditions for Callbacks -When writing conditional callbacks, it's possible to mix both +:if+ and +:unless+ in the same callback declaration. +When writing conditional callbacks, it is possible to mix both +:if+ and +:unless+ in the same callback declaration: class Comment < ActiveRecord::Base @@ -1140,7 +1142,7 @@ h3. Callback Classes Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them. -Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model. +Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model: class PictureFileCallbacks @@ -1152,7 +1154,7 @@ class PictureFileCallbacks end -When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way: +When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model: class PictureFile < ActiveRecord::Base @@ -1160,7 +1162,7 @@ class PictureFile < ActiveRecord::Base end -Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method. +Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of instantiated object. Often, however, it will make more sense to declare the callbacks as class methods: class PictureFileCallbacks @@ -1184,16 +1186,27 @@ You can declare as many callbacks as you want inside your callback classes. h3. Observers -Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add the same functionality outside of a model. For example, it could be argued that a +User+ model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn't directly related to your model, you may want to consider creating an observer instead. +Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add the same functionality without changing the code of the model. For example, it could be argued that a +User+ model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn't directly related to your model, you may want to consider creating an observer instead. h4. Creating Observers -For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we could create an observer to contain this functionality. +For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we should create an observer to contain the code implementing this functionality. + +Rails can create the initial code of the observers in a simple way. For instance, given a model +User+, the command $ rails generate observer User +generates file +app/models/user_observer.rb+ containing the observer class +UserObserver+: + + +class UserObserver < ActiveRecord::Observer +end + + +You may now add methods to be called at the desired occasions: + class UserObserver < ActiveRecord::Observer def after_create(model) @@ -1209,7 +1222,7 @@ h4. Registering Observers Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/application.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/application.rb+ this way: -# Activate observers that should always be running +# Activate observers that should always be running. config.active_record.observers = :user_observer @@ -1217,7 +1230,7 @@ As usual, settings in +config/environments+ take precedence over those in +confi h4. Sharing Observers -By default, Rails will simply strip "Observer" from an observer's name to find the model it should observe. However, observers can also be used to add behavior to more than one model, and so it's possible to manually specify the models that our observer should observe. +By default, Rails will simply strip "Observer" from an observer's name to find the model it should observe. However, observers can also be used to add behavior to more than one model, and thus it is possible to explicitly specify the models that our observer should observe: class MailerObserver < ActiveRecord::Observer @@ -1229,10 +1242,10 @@ class MailerObserver < ActiveRecord::Observer end -In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in +config/application.rb+ in order to take effect. +In this example, the +after_create+ method will be called whenever a +Registration+ or +User+ is created. Note that this new +MailerObserver+ would also need to be registered in +config/application.rb+ in order to take effect: -# Activate observers that should always be running +# Activate observers that should always be running. config.active_record.observers = :mailer_observer @@ -1240,7 +1253,7 @@ h3. Transaction Callbacks There are two additional callbacks that are triggered by the completion of a database transaction: +after_commit+ and +after_rollback+. These callbacks are very similar to the +after_save+ callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction. -Consider, for example, the previous example where the +PictureFile+ model needs to delete a file after a record is destroyed. If anything raises an exception after the +after_destroy+ callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that +picture_file_2+ in the code below is not valid and the +save!+ method raises an error. +Consider, for example, the previous example where the +PictureFile+ model needs to delete a file after the corresponding record is destroyed. If anything raises an exception after the +after_destroy+ callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that +picture_file_2+ in the code below is not valid and the +save!+ method raises an error. PictureFile.transaction do -- cgit v1.2.3 From a44bbfc1c7edb044ed9f73c7365a3a4a30b8b3fc Mon Sep 17 00:00:00 2001 From: Hendy Tanata Date: Wed, 5 Oct 2011 17:35:58 +0800 Subject: Corrections to Active Record Validations and Callbacks guide. --- railties/guides/source/active_record_validations_callbacks.textile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 6c6f29be32..600681ddd3 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -105,7 +105,7 @@ Person.create(:name => "John Doe").valid? # => true Person.create(:name => nil).valid? # => false -After Active Record performing validations, any errors found can be accessed through the +errors+ instance method, which returns a collection of errors. By definition an object is valid if this collection is empty after running validations. +After Active Record has performed validations, any errors found can be accessed through the +errors+ instance method, which returns a collection of errors. By definition, an object is valid if this collection is empty after running validations. Note that an object instantiated with +new+ will not report errors even if it's technically invalid, because validations are not run when using +new+. @@ -812,7 +812,7 @@ Add this line in your Gemfile: gem "dynamic_form" -Now you will have access to the two help methods +error_messages+ and +error_messages_for+ in your view templates. +Now you will have access to the two helper methods +error_messages+ and +error_messages_for+ in your view templates. h4. +error_messages+ and +error_messages_for+ @@ -907,7 +907,7 @@ ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| end -The result look like the following: +The result looks like the following: !images/validation_error_messages.png(Validation error messages)! -- cgit v1.2.3 From ea49935a6e0eca8783bc8d1bb46a6c518c073cac Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 5 Oct 2011 18:40:45 +0530 Subject: copy editing --- railties/guides/source/active_record_validations_callbacks.textile | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 600681ddd3..2a1e9bfc0c 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -1192,13 +1192,11 @@ h4. Creating Observers For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we should create an observer to contain the code implementing this functionality. -Rails can create the initial code of the observers in a simple way. For instance, given a model +User+, the command - $ rails generate observer User -generates file +app/models/user_observer.rb+ containing the observer class +UserObserver+: +generates +app/models/user_observer.rb+ containing the observer class +UserObserver+: class UserObserver < ActiveRecord::Observer -- cgit v1.2.3 From 8d775d5f1d58e5c0d881383e8c6e869d1d360c8c Mon Sep 17 00:00:00 2001 From: Manuel Menezes de Sequeira Date: Wed, 5 Oct 2011 22:14:41 +0100 Subject: Correction of code snippet tag from shell to ruby. --- railties/guides/source/active_record_validations_callbacks.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 600681ddd3..9346a408e0 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -46,7 +46,7 @@ end We can see how it works by looking at some +rails console+ output: - + >> p = Person.new(:name => "John Doe") => # >> p.new_record? @@ -55,7 +55,7 @@ We can see how it works by looking at some +rails console+ output: => true >> p.new_record? => false - + Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated. -- cgit v1.2.3 From b2deeabffb542bb1683571db4f1a69a3426f838f Mon Sep 17 00:00:00 2001 From: mhutchin Date: Sat, 8 Oct 2011 01:58:57 -0700 Subject: Correct stylesheet filename and remove reference to old stylesheet compilation location --- railties/guides/source/active_record_validations_callbacks.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 781b9001b6..2f78f1d0c8 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -880,7 +880,7 @@ The selectors used to customize the style of error messages are: * +#error_explanation p+ - Style for the paragraph holding the message that appears right below the header of the +div+ element. * +#error_explanation ul li+ - Style for the list items with individual error messages. -If scaffolding was used, file +app/assets/stylesheets/scaffold.css.scss+ (which later compiles to +app/assets/stylesheets/scaffold.css+), will have been generated automatically. This file defines the red-based styles you saw in the examples above. +If scaffolding was used, file +app/assets/stylesheets/scaffolds.css.scss+ will have been generated automatically. This file defines the red-based styles you saw in the examples above. The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers. -- cgit v1.2.3 From 62c03816e8b034ad0265548fe599667af6de5e87 Mon Sep 17 00:00:00 2001 From: mhutchin Date: Sat, 8 Oct 2011 03:59:13 -0700 Subject: copy editing "updated the ajax_on_rails.textile for rails3" --- railties/guides/source/active_record_validations_callbacks.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 2f78f1d0c8..665e7f9ccc 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -1162,7 +1162,7 @@ class PictureFile < ActiveRecord::Base end -Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of instantiated object. Often, however, it will make more sense to declare the callbacks as class methods: +Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of the instantiated object. Often, however, it will make more sense to declare the callbacks as class methods: class PictureFileCallbacks -- cgit v1.2.3 From b3c1cfa2772e64b20681bae8e765f37660087b18 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 2 Nov 2011 23:01:30 +0530 Subject: minor edits in AR validations guide --- .../source/active_record_validations_callbacks.textile | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 665e7f9ccc..4c1f66aedf 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -796,17 +796,9 @@ person.errors.size # => 0 h3. Displaying Validation Errors in the View -Rails maintains an official plugin, DynamicForm, that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem. +"DynamicForm":https://github.com/joelmoss/dynamic_form provides helpers to display the error messages of your models in your view templates. -h4. Installing as a plugin - - -$ rails plugin install git://github.com/joelmoss/dynamic_form.git - - -h4. Installing as a Gem - -Add this line in your Gemfile: +You can install it as a gem by adding this line to your Gemfile: gem "dynamic_form" -- cgit v1.2.3 From bcd25e7576094a98dbc9f4b1ba2fb3451d13bf40 Mon Sep 17 00:00:00 2001 From: Florian Walch Date: Sat, 5 Nov 2011 13:34:01 +0100 Subject: Fixed after_initialize/after_find guide Defining after_initialize and after_find as ordinary methods like documented in the guide doesn't work with Rails 3.1.1; now macro-style is used here, too. --- railties/guides/source/active_record_validations_callbacks.textile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties/guides/source/active_record_validations_callbacks.textile') diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile index 4c1f66aedf..a27c292a4c 100644 --- a/railties/guides/source/active_record_validations_callbacks.textile +++ b/railties/guides/source/active_record_validations_callbacks.textile @@ -978,15 +978,15 @@ The +after_initialize+ callback will be called whenever an Active Record object The +after_find+ callback will be called whenever Active Record loads a record from the database. +after_find+ is called before +after_initialize+ if both are defined. -The +after_initialize+ and +after_find+ callbacks are a bit different from the others. They have no +before_*+ counterparts, and they are registered simply by defining them as regular methods with predefined names. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behavior is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, which would otherwise significantly slow down the queries. +The +after_initialize+ and +after_find+ callbacks have no +before_*+ counterparts, but they can be registered just like the other Active Record callbacks. class User < ActiveRecord::Base - def after_initialize + after_initialize do |user| puts "You have initialized an object!" end - def after_find + after_find do |user| puts "You have found an object!" end end -- cgit v1.2.3