aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/source/activerecord_validations_callbacks.txt
diff options
context:
space:
mode:
authorPratik Naik <pratiknaik@gmail.com>2008-12-19 14:27:43 +0000
committerPratik Naik <pratiknaik@gmail.com>2008-12-19 14:27:43 +0000
commitc3f53f412cd170fc295b46e48aa81837ad15ec83 (patch)
tree79de6effe9874f3d17eada3666c13b5f76fa537c /railties/doc/guides/source/activerecord_validations_callbacks.txt
parent89b75814045e811d52b19278ae27b5f45c6d9dd6 (diff)
downloadrails-c3f53f412cd170fc295b46e48aa81837ad15ec83.tar.gz
rails-c3f53f412cd170fc295b46e48aa81837ad15ec83.tar.bz2
rails-c3f53f412cd170fc295b46e48aa81837ad15ec83.zip
Merge docrails
Diffstat (limited to 'railties/doc/guides/source/activerecord_validations_callbacks.txt')
-rw-r--r--railties/doc/guides/source/activerecord_validations_callbacks.txt75
1 files changed, 50 insertions, 25 deletions
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
index 0c82f24e66..e0bb534d0b 100644
--- a/railties/doc/guides/source/activerecord_validations_callbacks.txt
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -47,7 +47,7 @@ We can see how it works by looking at the following script/console output:
=> false
------------------------------------------------------------------
-Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
+Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use these facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
CAUTION: There are four methods that when called will trigger validation: +save+, +save!+, +update_attributes+ and +update_attributes!+. There is one method left, which is +update_attribute+. This method will update the value of an attribute without triggering any validation, so be careful when using +update_attribute+, since it can let you save your objects in an invalid state.
@@ -155,7 +155,8 @@ This helper validates that the attributes' values are not included in a given se
[source, ruby]
------------------------------------------------------------------
class MovieFile < ActiveRecord::Base
- validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
+ validates_exclusion_of :format, :in => %w(mov avi),
+ :message => "Extension %s is not allowed"
end
------------------------------------------------------------------
@@ -170,7 +171,8 @@ This helper validates the attributes's values by testing if they match a given p
[source, ruby]
------------------------------------------------------------------
class Product < ActiveRecord::Base
- validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
+ validates_format_of :description, :with => /^[a-zA-Z]+$/,
+ :message => "Only letters allowed"
end
------------------------------------------------------------------
@@ -183,7 +185,8 @@ This helper validates that the attributes' values are included in a given set. I
[source, ruby]
------------------------------------------------------------------
class Coffee < ActiveRecord::Base
- validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
+ validates_inclusion_of :size, :in => %w(small medium large),
+ :message => "%s is not a valid size"
end
------------------------------------------------------------------
@@ -223,7 +226,7 @@ end
This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to.
-=== The +validates_numericallity_of+ helper
+=== The +validates_numericality_of+ helper
This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed.
@@ -232,12 +235,12 @@ If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z
[source, ruby]
------------------------------------------------------------------
class Player < ActiveRecord::Base
- validates_numericallity_of :points
- validates_numericallity_of :games_played, :integer_only => true
+ validates_numericality_of :points
+ validates_numericality_of :games_played, :integer_only => true
end
------------------------------------------------------------------
-The default error message for +validates_numericallity_of+ is "_is not a number_".
+The default error message for +validates_numericality_of+ is "_is not a number_".
=== The +validates_presence_of+ helper
@@ -282,7 +285,8 @@ There is a +:scope+ option that you can use to specify other attributes that mus
[source, ruby]
------------------------------------------------------------------
class Holiday < ActiveRecord::Base
- validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
+ validates_uniqueness_of :name, :scope => :year,
+ :message => "Should happen once per year"
end
------------------------------------------------------------------
@@ -324,9 +328,14 @@ As stated before, the +:on+ option lets you specify when the validation should h
[source, ruby]
------------------------------------------------------------------
class Person < ActiveRecord::Base
- validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
- validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
- validates_presence_of :name, :on => :save # => that's the default
+ # => it will be possible to update email with a duplicated value
+ validates_uniqueness_of :email, :on => :create
+
+ # => it will be possible to create the record with a 'non-numerical age'
+ validates_numericality_of :age, :on => :update
+
+ # => the default
+ validates_presence_of :name, :on => :save
end
------------------------------------------------------------------
@@ -367,7 +376,8 @@ Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object
[source, ruby]
------------------------------------------------------------------
class Account < ActiveRecord::Base
- validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
+ validates_confirmation_of :password,
+ :unless => Proc.new { |a| a.password.blank? }
end
------------------------------------------------------------------
@@ -379,7 +389,8 @@ When the built-in validation helpers are not enough for your needs, you can writ
------------------------------------------------------------------
class Invoice < ActiveRecord::Base
def validate_on_create
- errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ errors.add(:expiration_date, "can't be in the past") if
+ !expiration_date.blank? and expiration_date < Date.today
end
end
------------------------------------------------------------------
@@ -389,14 +400,17 @@ If your validation rules are too complicated and you want to break them in small
[source, ruby]
------------------------------------------------------------------
class Invoice < ActiveRecord::Base
- validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
+ validate :expiration_date_cannot_be_in_the_past,
+ :discount_cannot_be_more_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
+ errors.add(:expiration_date, "can't be in the past") if
+ !expiration_date.blank? and expiration_date < Date.today
end
def discount_cannot_be_greater_than_total_value
- errors.add(:discount, "can't be greater than total value") unless discount <= total_value
+ errors.add(:discount, "can't be greater than total value") unless
+ discount <= total_value
end
end
------------------------------------------------------------------
@@ -454,14 +468,16 @@ person.errors.on(:name) # => nil
person = Person.new(:name => "JD")
person.valid? # => false
-person.errors.on(:name) # => "is too short (minimum is 3 characters)"
+person.errors.on(:name)
+# => "is too short (minimum is 3 characters)"
person = Person.new
person.valid? # => false
-person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
+person.errors.on(:name)
+# => ["can't be blank", "is too short (minimum is 3 characters)"]
------------------------------------------------------------------
-* +clear+ is used when you intentionally wants to clear all the messages in the +errors+ collection.
+* +clear+ is used when you intentionally want to clear all the messages in the +errors+ collection. However, calling +errors.clear+ upon an invalid object won't 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. If any of them fails, the +errors+ collection will get filled again.
[source, ruby]
------------------------------------------------------------------
@@ -471,10 +487,15 @@ class Person < ActiveRecord::Base
end
person = Person.new
-puts person.valid? # => false
-person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
+person.valid? # => false
+person.errors.on(:name)
+# => ["can't be blank", "is too short (minimum is 3 characters)"]
+
person.errors.clear
-person.errors # => nil
+person.errors.empty? # => true
+p.save # => false
+p.errors.on(:name)
+# => ["can't be blank", "is too short (minimum is 3 characters)"]
------------------------------------------------------------------
== Callbacks
@@ -587,7 +608,7 @@ The +after_initialize+ and +after_find+ callbacks are a bit different from the o
== 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. However, if at any moment one of the callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
+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. However, if at any moment one of the +before_create+, +before_save+, +before_update+ or +before_destroy+ callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
== Callback classes
@@ -667,7 +688,7 @@ end
=== 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 then 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.
+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.
[source, ruby]
------------------------------------------------------------------
@@ -675,6 +696,10 @@ If you payed attention, you may be wondering where Active Record Observers are r
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.
+
=== Where to put the observers' source files
By convention, you should always save your observers' source files inside *app/models*.