mirror of
https://github.com/github/rails.git
synced 2026-04-26 03:00:59 -04:00
Fix custom validation methods section in AR validations and callbacks guide
The methods validate_on_create and validate_on_update are not available anymore in Rails, this removes them from the guide and adds an example on how to use validate with the :on option.
This commit is contained in:
@@ -614,7 +614,7 @@ As shown in the example, you can also combine standard validations with your own
|
||||
|
||||
h4. Custom Methods
|
||||
|
||||
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.
|
||||
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 the +validate+ class method, passing in the symbols for the validation methods' names.
|
||||
|
||||
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.
|
||||
|
||||
@@ -637,12 +637,24 @@ class Invoice < ActiveRecord::Base
|
||||
end
|
||||
</ruby>
|
||||
|
||||
By default such validations will run every time you call +valid?+. It is also possible to control when to run these custom validations by giving an +:on+ option to the +validate+ method, with either: +:create+ or +:update+.
|
||||
|
||||
<ruby>
|
||||
class Invoice < ActiveRecord::Base
|
||||
validate :active_customer, :on => :create
|
||||
|
||||
def active_customer
|
||||
errors.add(:customer_id, "is not active") unless customer.active?
|
||||
end
|
||||
end
|
||||
</ruby>
|
||||
|
||||
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:
|
||||
|
||||
<ruby>
|
||||
ActiveRecord::Base.class_eval do
|
||||
def self.validates_as_choice(attr_name, n, options={})
|
||||
validates attr_name, :inclusion => { {:in => 1..n}.merge(options) }
|
||||
validates attr_name, :inclusion => { { :in => 1..n }.merge!(options) }
|
||||
end
|
||||
end
|
||||
</ruby>
|
||||
|
||||
Reference in New Issue
Block a user