2 # Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
3 # +record+ method to retrieve the record which did not validate.
5 # complex_operation_that_calls_save!_internally
6 # rescue ActiveRecord::RecordInvalid => invalid
7 # puts invalid.record.errors
9 class RecordInvalid
< ActiveRecordError
11 def initialize(record
)
13 super("Validation failed: #{@record.errors.full_messages.join(", ")}")
17 # Active Record validation is reported to and from this object, which is used by Base#save to
18 # determine whether the object is in a valid state to be saved. See usage example in Validations.
23 def default_error_messages
24 ActiveSupport
::Deprecation.warn("ActiveRecord::Errors.default_error_messages has been deprecated. Please use I18n.translate('activerecord.errors.messages').")
25 I18n
.translate
'activerecord.errors.messages'
29 def initialize(base
) # :nodoc:
30 @base, @errors = base
, {}
33 # Adds an error to the base object instead of any particular attribute. This is used
34 # to report errors that don't tie to any specific attribute, but rather to the object
35 # as a whole. These error messages don't get prepended with any field name when iterating
36 # with +each_full+, so they should be complete sentences.
41 # Adds an error message (+messsage+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
42 # for the same attribute and ensure that this error object returns false when asked if <tt>empty?</tt>. More than one
43 # error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
44 # If no +messsage+ is supplied, :invalid is assumed.
45 # If +message+ is a Symbol, it will be translated, using the appropriate scope (see translate_error).
46 def add(attribute
, message
= nil, options
= {})
48 message
= generate_message(attribute
, message
, options
) if message
.is_a
?(Symbol
)
49 @errors[attribute
.to_s
] ||= []
50 @errors[attribute
.to_s
] << message
53 # Will add an error message to each of the attributes in +attributes+ that is empty.
54 def add_on_empty(attributes
, custom_message
= nil)
55 for attr
in [attributes
].flatten
56 value
= @base.respond_to
?(attr
.to_s
) ? @base.send(attr
.to_s
) : @base[attr
.to_s
]
57 is_empty
= value
.respond_to
?(:empty?) ? value
.empty
? : false
58 add(attr
, :empty, :default => custom_message
) unless !value
.nil? && !is_empty
62 # Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
63 def add_on_blank(attributes
, custom_message
= nil)
64 for attr
in [attributes
].flatten
65 value
= @base.respond_to
?(attr
.to_s
) ? @base.send(attr
.to_s
) : @base[attr
.to_s
]
66 add(attr
, :blank, :default => custom_message
) if value
.blank
?
70 # Translates an error message in it's default scope (<tt>activerecord.errrors.messages</tt>).
71 # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>, if it's not there,
72 # it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not there it returns the translation of the
73 # default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name,
74 # translated attribute name and the value are available for interpolation.
76 # When using inheritence in your models, it will check all the inherited models too, but only if the model itself
77 # hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt>
78 # error +message+ for the <tt>title</tt> +attribute+, it looks for these translations:
81 # <li><tt>activerecord.errors.models.admin.attributes.title.blank</tt></li>
82 # <li><tt>activerecord.errors.models.admin.blank</tt></li>
83 # <li><tt>activerecord.errors.models.user.attributes.title.blank</tt></li>
84 # <li><tt>activerecord.errors.models.user.blank</tt></li>
85 # <li><tt>activerecord.errors.messages.blank</tt></li>
86 # <li>any default you provided through the +options+ hash (in the activerecord.errors scope)</li>
88 def generate_message(attribute
, message
= :invalid, options
= {})
90 message
, options
[:default] = options
[:default], message
if options
[:default].is_a
?(Symbol
)
92 defaults
= @base.class.self_and_descendents_from_active_record
.map
do |klass
|
93 [ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{message}",
94 :"models.#{klass.name.underscore}.#{message}" ]
97 defaults
<< options
.delete(:default)
98 defaults
= defaults
.compact
.flatten
<< :"messages.#{message}"
101 value
= @base.respond_to
?(attribute
) ? @base.send(attribute
) : nil
103 options
= { :default => defaults
,
104 :model => @base.class.human_name
,
105 :attribute => @base.class.human_attribute_name(attribute
.to_s
),
107 :scope => [:activerecord, :errors]
110 I18n
.translate(key
, options
)
113 # Returns true if the specified +attribute+ has errors associated with it.
115 # class Company < ActiveRecord::Base
116 # validates_presence_of :name, :address, :email
117 # validates_length_of :name, :in => 5..30
120 # company = Company.create(:address => '123 First St.')
121 # company.errors.invalid?(:name) # => true
122 # company.errors.invalid?(:address) # => false
123 def invalid
?(attribute
)
124 !@errors[attribute
.to_s
].nil?
127 # Returns +nil+, if no errors are associated with the specified +attribute+.
128 # Returns the error message, if one error is associated with the specified +attribute+.
129 # Returns an array of error messages, if more than one error is associated with the specified +attribute+.
131 # class Company < ActiveRecord::Base
132 # validates_presence_of :name, :address, :email
133 # validates_length_of :name, :in => 5..30
136 # company = Company.create(:address => '123 First St.')
137 # company.errors.on(:name) # => ["is too short (minimum is 5 characters)", "can't be blank"]
138 # company.errors.on(:email) # => "can't be blank"
139 # company.errors.on(:address) # => nil
141 errors
= @errors[attribute
.to_s
]
142 return nil if errors
.nil?
143 errors
.size
== 1 ? errors
.first
: errors
148 # Returns errors assigned to the base object through +add_to_base+ according to the normal rules of <tt>on(attribute)</tt>.
153 # Yields each attribute and associated message per error added.
155 # class Company < ActiveRecord::Base
156 # validates_presence_of :name, :address, :email
157 # validates_length_of :name, :in => 5..30
160 # company = Company.create(:address => '123 First St.')
161 # company.errors.each{|attr,msg| puts "#{attr} - #{msg}" }
162 # # => name - is too short (minimum is 5 characters)
163 # # name - can't be blank
164 # # address - can't be blank
166 @errors.each_key
{ |attr
| @errors[attr
].each
{ |msg
| yield attr
, msg
} }
169 # Yields each full error message added. So <tt>Person.errors.add("first_name", "can't be empty")</tt> will be returned
170 # through iteration as "First name can't be empty".
172 # class Company < ActiveRecord::Base
173 # validates_presence_of :name, :address, :email
174 # validates_length_of :name, :in => 5..30
177 # company = Company.create(:address => '123 First St.')
178 # company.errors.each_full{|msg| puts msg }
179 # # => Name is too short (minimum is 5 characters)
180 # # Name can't be blank
181 # # Address can't be blank
183 full_messages
.each
{ |msg
| yield msg
}
186 # Returns all the full error messages in an array.
188 # class Company < ActiveRecord::Base
189 # validates_presence_of :name, :address, :email
190 # validates_length_of :name, :in => 5..30
193 # company = Company.create(:address => '123 First St.')
194 # company.errors.full_messages # =>
195 # ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
196 def full_messages(options
= {})
199 @errors.each_key
do |attr
|
200 @errors[attr
].each
do |message
|
204 full_messages
<< message
206 #key = :"activerecord.att.#{@base.class.name.underscore.to_sym}.#{attr}"
207 attr_name
= @base.class.human_attribute_name(attr
)
208 full_messages
<< attr_name
+ ' ' + message
215 # Returns true if no errors have been added.
220 # Removes all errors that have been added.
225 # Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
227 @errors.values
.inject(0) { |error_count
, attribute
| error_count
+ attribute
.size
}
230 alias_method
:count, :size
231 alias_method
:length, :size
233 # Returns an XML representation of this error object.
235 # class Company < ActiveRecord::Base
236 # validates_presence_of :name, :address, :email
237 # validates_length_of :name, :in => 5..30
240 # company = Company.create(:address => '123 First St.')
241 # company.errors.to_xml
242 # # => <?xml version="1.0" encoding="UTF-8"?>
244 # # <error>Name is too short (minimum is 5 characters)</error>
245 # # <error>Name can't be blank</error>
246 # # <error>Address can't be blank</error>
248 def to_xml(options
={})
249 options
[:root] ||= "errors"
250 options
[:indent] ||= 2
251 options
[:builder] ||= Builder
::XmlMarkup.new(:indent => options
[:indent])
253 options
[:builder].instruct
! unless options
.delete(:skip_instruct)
254 options
[:builder].errors
do |e
|
255 full_messages
.each
{ |msg
| e
.error(msg
) }
262 # Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
264 # Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
265 # +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
266 # that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
270 # class Person < ActiveRecord::Base
273 # errors.add_on_empty %w( first_name last_name )
274 # errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
277 # def validate_on_create # is only run the first time a new object is saved
278 # unless valid_discount?(membership_discount)
279 # errors.add("membership_discount", "has expired")
283 # def validate_on_update
284 # errors.add_to_base("No changes have occurred") if unchanged_attributes?
288 # person = Person.new("first_name" => "David", "phone_number" => "what?")
289 # person.save # => false (and doesn't do the save)
290 # person.errors.empty? # => false
291 # person.errors.count # => 2
292 # person.errors.on "last_name" # => "can't be empty"
293 # person.errors.on "phone_number" # => "has invalid format"
294 # person.errors.each_full { |msg| puts msg }
295 # # => "Last name can't be empty\n" +
296 # # "Phone number has invalid format"
298 # person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
299 # person.save # => true (and person is now saved in the database)
301 # An Errors object is automatically created for every Active Record.
303 VALIDATIONS
= %w( validate validate_on_create validate_on_update
)
305 def self.included(base
) # :nodoc:
306 base
.extend ClassMethods
308 alias_method_chain
:save, :validation
309 alias_method_chain
:save!, :validation
312 base
.send
:include, ActiveSupport
::Callbacks
313 base
.define_callbacks
*VALIDATIONS
316 # Active Record classes can implement validations in several ways. The highest level, easiest to read,
317 # and recommended approach is to use the declarative <tt>validates_..._of</tt> class methods (and
318 # +validates_associated+) documented below. These are sufficient for most model validations.
320 # Slightly lower level is +validates_each+. It provides some of the same options as the purely declarative
321 # validation methods, but like all the lower-level approaches it requires manually adding to the errors collection
322 # when the record is invalid.
324 # At a yet lower level, a model can use the class methods +validate+, +validate_on_create+ and +validate_on_update+
325 # to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance
328 # The lowest level style is to define the instance methods +validate+, +validate_on_create+ and +validate_on_update+
329 # as documented in ActiveRecord::Validations.
331 # == +validate+, +validate_on_create+ and +validate_on_update+ Class Methods
333 # Calls to these methods add a validation method or block to the class. Again, this approach is recommended
334 # only when the higher-level methods documented below (<tt>validates_..._of</tt> and +validates_associated+) are
335 # insufficient to handle the required validation.
337 # This can be done with a symbol pointing to a method:
339 # class Comment < ActiveRecord::Base
340 # validate :must_be_friends
342 # def must_be_friends
343 # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
347 # Or with a block which is passed the current record to be validated:
349 # class Comment < ActiveRecord::Base
350 # validate do |comment|
351 # comment.must_be_friends
354 # def must_be_friends
355 # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
359 # This usage applies to +validate_on_create+ and +validate_on_update+ as well.
361 DEFAULT_VALIDATION_OPTIONS
= {
364 :allow_blank => false,
368 ALL_RANGE_OPTIONS
= [ :is, :within, :in, :minimum, :maximum ].freeze
369 ALL_NUMERICALITY_CHECKS
= { :greater_than => '>', :greater_than_or_equal_to => '>=',
370 :equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
371 :odd => 'odd?', :even => 'even?' }.freeze
373 # Validates each attribute against a block.
375 # class Person < ActiveRecord::Base
376 # validates_each :first_name, :last_name do |record, attr, value|
377 # record.errors.add attr, 'starts with z.' if value[0] == ?z
382 # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
383 # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
384 # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
385 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
386 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
387 # method, proc or string should return or evaluate to a true or false value.
388 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
389 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
390 # method, proc or string should return or evaluate to a true or false value.
391 def validates_each(*attrs
)
392 options
= attrs
.extract_options
!.symbolize_keys
393 attrs
= attrs
.flatten
395 # Declare the validation.
396 send(validation_method(options
[:on] || :save), options
) do |record
|
398 value
= record
.send(attr
)
399 next if (value
.nil? && options
[:allow_nil]) || (value
.blank
? && options
[:allow_blank])
400 yield record
, attr
, value
405 # Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
408 # class Person < ActiveRecord::Base
409 # validates_confirmation_of :user_name, :password
410 # validates_confirmation_of :email_address, :message => "should match confirmation"
414 # <%= password_field "person", "password" %>
415 # <%= password_field "person", "password_confirmation" %>
417 # The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
418 # To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
419 # only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
420 # check for the confirmation attribute:
422 # validates_presence_of :password_confirmation, :if => :password_changed?
424 # Configuration options:
425 # * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation").
426 # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
427 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
428 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
429 # method, proc or string should return or evaluate to a true or false value.
430 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
431 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
432 # method, proc or string should return or evaluate to a true or false value.
433 def validates_confirmation_of(*attr_names
)
434 configuration
= { :on => :save }
435 configuration
.update(attr_names
.extract_options
!)
437 attr_accessor(*(attr_names
.map
{ |n
| "#{n}_confirmation" }))
439 validates_each(attr_names
, configuration
) do |record
, attr_name
, value
|
440 unless record
.send("#{attr_name}_confirmation").nil? or value
== record
.send("#{attr_name}_confirmation")
441 record
.errors
.add(attr_name
, :confirmation, :default => configuration
[:message])
446 # Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
448 # class Person < ActiveRecord::Base
449 # validates_acceptance_of :terms_of_service
450 # validates_acceptance_of :eula, :message => "must be abided"
453 # If the database column does not exist, the +terms_of_service+ attribute is entirely virtual. This check is
454 # performed only if +terms_of_service+ is not +nil+ and by default on save.
456 # Configuration options:
457 # * <tt>:message</tt> - A custom error message (default is: "must be accepted").
458 # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
459 # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is true).
460 # * <tt>:accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
461 # makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
462 # column, since the attribute is typecast from "1" to +true+ before validation.
463 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
464 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
465 # method, proc or string should return or evaluate to a true or false value.
466 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
467 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
468 # method, proc or string should return or evaluate to a true or false value.
469 def validates_acceptance_of(*attr_names
)
470 configuration
= { :on => :save, :allow_nil => true, :accept => "1" }
471 configuration
.update(attr_names
.extract_options
!)
475 rescue Exception
# To ignore both statement and connection errors
478 names
= attr_names
.reject
{ |name
| db_cols
.include?(name
.to_s
) }
479 attr_accessor(*names
)
481 validates_each(attr_names
,configuration
) do |record
, attr_name
, value
|
482 unless value
== configuration
[:accept]
483 record
.errors
.add(attr_name
, :accepted, :default => configuration
[:message])
488 # Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
490 # class Person < ActiveRecord::Base
491 # validates_presence_of :first_name
494 # The first_name attribute must be in the object and it cannot be blank.
496 # If you want to validate the presence of a boolean field (where the real values are true and false),
497 # you will want to use validates_inclusion_of :field_name, :in => [true, false]
498 # This is due to the way Object#blank? handles boolean values. false.blank? # => true
500 # Configuration options:
501 # * <tt>message</tt> - A custom error message (default is: "can't be blank").
502 # * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
503 # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
504 # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
505 # method, proc or string should return or evaluate to a true or false value.
506 # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
507 # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
508 # method, proc or string should return or evaluate to a true or false value.
510 def validates_presence_of(*attr_names
)
511 configuration
= { :on => :save }
512 configuration
.update(attr_names
.extract_options
!)
514 # can't use validates_each here, because it cannot cope with nonexistent attributes,
515 # while errors.add_on_empty can
516 send(validation_method(configuration
[:on]), configuration
) do |record
|
517 record
.errors
.add_on_blank(attr_names
, configuration
[:message])
521 # Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
523 # class Person < ActiveRecord::Base
524 # validates_length_of :first_name, :maximum=>30
525 # validates_length_of :last_name, :maximum=>30, :message=>"less than {{count}} if you don't mind"
526 # validates_length_of :fax, :in => 7..32, :allow_nil => true
527 # validates_length_of :phone, :in => 7..32, :allow_blank => true
528 # validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
529 # validates_length_of :fav_bra_size, :minimum => 1, :too_short => "please enter at least {{count}} character"
530 # validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with {{count}} characters... don't play me."
531 # validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least {{count}} words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
534 # Configuration options:
535 # * <tt>:minimum</tt> - The minimum size of the attribute.
536 # * <tt>:maximum</tt> - The maximum size of the attribute.
537 # * <tt>:is</tt> - The exact size of the attribute.
538 # * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
539 # * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
540 # * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
541 # * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
542 # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is {{count}} characters)").
543 # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is {{count}} characters)").
544 # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be {{count}} characters)").
545 # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
546 # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
547 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
548 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
549 # method, proc or string should return or evaluate to a true or false value.
550 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
551 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
552 # method, proc or string should return or evaluate to a true or false value.
553 # * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
554 # count words as in above example.)
555 # Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
556 def validates_length_of(*attrs
)
557 # Merge given options with defaults.
559 :tokenizer => lambda
{|value
| value
.split(//)}
560 }.merge(DEFAULT_VALIDATION_OPTIONS
)
561 options
.update(attrs
.extract_options
!.symbolize_keys
)
563 # Ensure that one and only one range option is specified.
564 range_options
= ALL_RANGE_OPTIONS
& options
.keys
565 case range_options
.size
567 raise ArgumentError
, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
569 # Valid number of options; do nothing.
571 raise ArgumentError
, 'Too many range options specified. Choose only one.'
574 # Get range option and value.
575 option
= range_options
.first
576 option_value
= options
[range_options
.first
]
580 raise ArgumentError
, ":#{option} must be a Range" unless option_value
.is_a
?(Range
)
582 validates_each(attrs
, options
) do |record
, attr
, value
|
583 value
= options
[:tokenizer].call(value
) if value
.kind_of
?(String
)
584 if value
.nil? or value
.size
< option_value
.begin
585 record
.errors
.add(attr
, :too_short, :default => options
[:too_short], :count => option_value
.begin)
586 elsif value
.size
> option_value
.end
587 record
.errors
.add(attr
, :too_long, :default => options
[:too_long], :count => option_value
.end)
590 when :is, :minimum, :maximum
591 raise ArgumentError
, ":#{option} must be a nonnegative Integer" unless option_value
.is_a
?(Integer
) and option_value
>= 0
593 # Declare different validations per option.
594 validity_checks
= { :is => "==", :minimum => ">=", :maximum => "<=" }
595 message_options
= { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }
597 validates_each(attrs
, options
) do |record
, attr
, value
|
598 value
= options
[:tokenizer].call(value
) if value
.kind_of
?(String
)
599 unless !value
.nil? and value
.size
.method(validity_checks
[option
])[option_value
]
600 key
= message_options
[option
]
601 custom_message
= options
[:message] || options
[key
]
602 record
.errors
.add(attr
, key
, :default => custom_message
, :count => option_value
)
608 alias_method
:validates_size_of, :validates_length_of
611 # Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
612 # can be named "davidhh".
614 # class Person < ActiveRecord::Base
615 # validates_uniqueness_of :user_name, :scope => :account_id
618 # It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example,
619 # making sure that a teacher can only be on the schedule once per semester for a particular class.
621 # class TeacherSchedule < ActiveRecord::Base
622 # validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
625 # When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified
626 # attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
628 # Configuration options:
629 # * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
630 # * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
631 # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default).
632 # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
633 # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
634 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
635 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
636 # method, proc or string should return or evaluate to a true or false value.
637 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
638 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
639 # method, proc or string should return or evaluate to a true or false value.
641 # === Concurrency and integrity
643 # Using this validation method in conjunction with ActiveRecord::Base#save
644 # does not guarantee the absence of duplicate record insertions, because
645 # uniqueness checks on the application level are inherently prone to race
646 # conditions. For example, suppose that two users try to post a Comment at
647 # the same time, and a Comment's title must be unique. At the database-level,
648 # the actions performed by these users could be interleaved in the following manner:
651 # ------------------------------------+--------------------------------------
652 # # User 1 checks whether there's |
653 # # already a comment with the title |
654 # # 'My Post'. This is not the case. |
655 # SELECT * FROM comments |
656 # WHERE title = 'My Post' |
658 # | # User 2 does the same thing and also
659 # | # infers that his title is unique.
660 # | SELECT * FROM comments
661 # | WHERE title = 'My Post'
663 # # User 1 inserts his comment. |
664 # INSERT INTO comments |
665 # (title, content) VALUES |
666 # ('My Post', 'hi!') |
668 # | # User 2 does the same thing.
669 # | INSERT INTO comments
670 # | (title, content) VALUES
671 # | ('My Post', 'hello!')
674 # | # Boom! We now have a duplicate
677 # This could even happen if you use transactions with the 'serializable'
678 # isolation level. There are several ways to get around this problem:
679 # - By locking the database table before validating, and unlocking it after
680 # saving. However, table locking is very expensive, and thus not
682 # - By locking a lock file before validating, and unlocking it after saving.
683 # This does not work if you've scaled your Rails application across
684 # multiple web servers (because they cannot share lock files, or cannot
685 # do that efficiently), and thus not recommended.
686 # - Creating a unique index on the field, by using
687 # ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
688 # rare case that a race condition occurs, the database will guarantee
689 # the field's uniqueness.
691 # When the database catches such a duplicate insertion,
692 # ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
693 # exception. You can either choose to let this error propagate (which
694 # will result in the default Rails exception page being shown), or you
695 # can catch it and restart the transaction (e.g. by telling the user
696 # that the title already exists, and asking him to re-enter the title).
697 # This technique is also known as optimistic concurrency control:
698 # http://en.wikipedia.org/wiki/Optimistic_concurrency_control
700 # Active Record currently provides no way to distinguish unique
701 # index constraint errors from other types of database errors, so you
702 # will have to parse the (database-specific) exception message to detect
704 def validates_uniqueness_of(*attr_names
)
705 configuration
= { :case_sensitive => true }
706 configuration
.update(attr_names
.extract_options
!)
708 validates_each(attr_names
,configuration
) do |record
, attr_name
, value
|
709 # The check for an existing value should be run from a class that
710 # isn't abstract. This means working down from the current class
711 # (self), to the first non-abstract class. Since classes don't know
712 # their subclasses, we have to build the hierarchy between self and
713 # the record's class.
714 class_hierarchy
= [record
.class]
715 while class_hierarchy
.first
!= self
716 class_hierarchy
.insert(0, class_hierarchy
.first
.superclass
)
719 # Now we can work our way down the tree to the first non-abstract
720 # class (which has a database table to query from).
721 finder_class
= class_hierarchy
.detect
{ |klass
| !klass
.abstract_class
? }
723 is_text_column
= finder_class
.columns_hash
[attr_name
.to_s
].text
?
726 comparison_operator
= "IS ?"
728 comparison_operator
= "#{connection.case_sensitive_equality_operator} ?"
731 comparison_operator
= "= ?"
734 sql_attribute
= "#{record.class.quoted_table_name}.#{connection.quote_column_name(attr_name)}"
736 if value
.nil? || (configuration
[:case_sensitive] || !is_text_column
)
737 condition_sql
= "#{sql_attribute} #{comparison_operator}"
738 condition_params
= [value
]
740 condition_sql
= "LOWER(#{sql_attribute}) #{comparison_operator}"
741 condition_params
= [value
.mb_chars
.downcase
]
744 if scope
= configuration
[:scope]
745 Array(scope
).map
do |scope_item
|
746 scope_value
= record
.send(scope_item
)
747 condition_sql
<< " AND #{record.class.quoted_table_name}.#{scope_item} #{attribute_condition(scope_value)}"
748 condition_params
<< scope_value
752 unless record
.new_record
?
753 condition_sql
<< " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?"
754 condition_params
<< record
.send(:id)
757 finder_class
.with_exclusive_scope
do
758 if finder_class
.exists
?([condition_sql
, *condition_params
])
759 record
.errors
.add(attr_name
, :taken, :default => configuration
[:message], :value => value
)
766 # Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
769 # class Person < ActiveRecord::Base
770 # validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
773 # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
775 # A regular expression must be provided or else an exception will be raised.
777 # Configuration options:
778 # * <tt>:message</tt> - A custom error message (default is: "is invalid").
779 # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
780 # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
781 # * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!).
782 # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
783 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
784 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
785 # method, proc or string should return or evaluate to a true or false value.
786 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
787 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
788 # method, proc or string should return or evaluate to a true or false value.
789 def validates_format_of(*attr_names
)
790 configuration
= { :on => :save, :with => nil }
791 configuration
.update(attr_names
.extract_options
!)
793 raise(ArgumentError
, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration
[:with].is_a
?(Regexp
)
795 validates_each(attr_names
, configuration
) do |record
, attr_name
, value
|
796 unless value
.to_s
=~ configuration
[:with]
797 record
.errors
.add(attr_name
, :invalid, :default => configuration
[:message], :value => value
)
802 # Validates whether the value of the specified attribute is available in a particular enumerable object.
804 # class Person < ActiveRecord::Base
805 # validates_inclusion_of :gender, :in => %w( m f ), :message => "woah! what are you then!??!!"
806 # validates_inclusion_of :age, :in => 0..99
807 # validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension {{value}} is not included in the list"
810 # Configuration options:
811 # * <tt>:in</tt> - An enumerable object of available items.
812 # * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
813 # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
814 # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
815 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
816 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
817 # method, proc or string should return or evaluate to a true or false value.
818 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
819 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
820 # method, proc or string should return or evaluate to a true or false value.
821 def validates_inclusion_of(*attr_names
)
822 configuration
= { :on => :save }
823 configuration
.update(attr_names
.extract_options
!)
825 enum
= configuration
[:in] || configuration
[:within]
827 raise(ArgumentError
, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum
.respond_to
?(:include?)
829 validates_each(attr_names
, configuration
) do |record
, attr_name
, value
|
830 unless enum
.include?(value
)
831 record
.errors
.add(attr_name
, :inclusion, :default => configuration
[:message], :value => value
)
836 # Validates that the value of the specified attribute is not in a particular enumerable object.
838 # class Person < ActiveRecord::Base
839 # validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
840 # validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
841 # validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension {{value}} is not allowed"
844 # Configuration options:
845 # * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
846 # * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
847 # * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
848 # * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
849 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
850 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
851 # method, proc or string should return or evaluate to a true or false value.
852 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
853 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
854 # method, proc or string should return or evaluate to a true or false value.
855 def validates_exclusion_of(*attr_names
)
856 configuration
= { :on => :save }
857 configuration
.update(attr_names
.extract_options
!)
859 enum
= configuration
[:in] || configuration
[:within]
861 raise(ArgumentError
, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum
.respond_to
?(:include?)
863 validates_each(attr_names
, configuration
) do |record
, attr_name
, value
|
864 if enum
.include?(value
)
865 record
.errors
.add(attr_name
, :exclusion, :default => configuration
[:message], :value => value
)
870 # Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
872 # class Book < ActiveRecord::Base
874 # belongs_to :library
876 # validates_associated :pages, :library
879 # Warning: If, after the above definition, you then wrote:
881 # class Page < ActiveRecord::Base
884 # validates_associated :book
887 # this would specify a circular dependency and cause infinite recursion.
889 # NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
890 # is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
892 # Configuration options:
893 # * <tt>:message</tt> - A custom error message (default is: "is invalid")
894 # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
895 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
896 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
897 # method, proc or string should return or evaluate to a true or false value.
898 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
899 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
900 # method, proc or string should return or evaluate to a true or false value.
901 def validates_associated(*attr_names
)
902 configuration
= { :on => :save }
903 configuration
.update(attr_names
.extract_options
!)
905 validates_each(attr_names
, configuration
) do |record
, attr_name
, value
|
906 unless (value
.is_a
?(Array
) ? value
: [value
]).inject(true) { |v
, r
| (r
.nil? || r
.valid
?) && v
}
907 record
.errors
.add(attr_name
, :invalid, :default => configuration
[:message], :value => value
)
912 # Validates whether the value of the specified attribute is numeric by trying to convert it to
913 # a float with Kernel.Float (if <tt>only_integer</tt> is false) or applying it to the regular expression
914 # <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>only_integer</tt> is set to true).
916 # class Person < ActiveRecord::Base
917 # validates_numericality_of :value, :on => :create
920 # Configuration options:
921 # * <tt>:message</tt> - A custom error message (default is: "is not a number").
922 # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
923 # * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
924 # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+.
925 # * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
926 # * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value.
927 # * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
928 # * <tt>:less_than</tt> - Specifies the value must be less than the supplied value.
929 # * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value.
930 # * <tt>:odd</tt> - Specifies the value must be an odd number.
931 # * <tt>:even</tt> - Specifies the value must be an even number.
932 # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
933 # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
934 # method, proc or string should return or evaluate to a true or false value.
935 # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
936 # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
937 # method, proc or string should return or evaluate to a true or false value.
938 def validates_numericality_of(*attr_names
)
939 configuration
= { :on => :save, :only_integer => false, :allow_nil => false }
940 configuration
.update(attr_names
.extract_options
!)
943 numericality_options
= ALL_NUMERICALITY_CHECKS
.keys
& configuration
.keys
945 (numericality_options
- [ :odd, :even ]).each
do |option
|
946 raise ArgumentError
, ":#{option} must be a number" unless configuration
[option
].is_a
?(Numeric
)
949 validates_each(attr_names
,configuration
) do |record
, attr_name
, value
|
950 raw_value
= record
.send("#{attr_name}_before_type_cast") || value
952 next if configuration
[:allow_nil] and raw_value
.nil?
954 if configuration
[:only_integer]
955 unless raw_value
.to_s
=~
/\A[+-]?\d+\Z/
956 record
.errors
.add(attr_name
, :not_a_number, :value => raw_value
, :default => configuration
[:message])
959 raw_value
= raw_value
.to_i
962 raw_value
= Kernel
.Float(raw_value
)
963 rescue ArgumentError
, TypeError
964 record
.errors
.add(attr_name
, :not_a_number, :value => raw_value
, :default => configuration
[:message])
969 numericality_options
.each
do |option
|
972 unless raw_value
.to_i
.method(ALL_NUMERICALITY_CHECKS
[option
])[]
973 record
.errors
.add(attr_name
, option
, :value => raw_value
, :default => configuration
[:message])
976 record
.errors
.add(attr_name
, option
, :default => configuration
[:message], :value => raw_value
, :count => configuration
[option
]) unless raw_value
.method(ALL_NUMERICALITY_CHECKS
[option
])[configuration
[option
]]
982 # Creates an object just like Base.create but calls save! instead of save
983 # so an exception is raised if the record is invalid.
984 def create
!(attributes
= nil, &block
)
985 if attributes
.is_a
?(Array
)
986 attributes
.collect
{ |attr
| create
!(attr
, &block
) }
988 object
= new(attributes
)
989 yield(object
) if block_given
?
996 def validation_method(on
)
998 when :save then :validate
999 when :create then :validate_on_create
1000 when :update then :validate_on_update
1005 # The validation process on save can be skipped by passing false. The regular Base#save method is
1006 # replaced with this when the validations module is mixed in, which it is by default.
1007 def save_with_validation(perform_validation
= true)
1008 if perform_validation
&& valid
? || !perform_validation
1009 save_without_validation
1015 # Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
1016 # if the record is not valid.
1017 def save_with_validation
!
1019 save_without_validation
!
1021 raise RecordInvalid
.new(self)
1025 # Runs +validate+ and +validate_on_create+ or +validate_on_update+ and returns true if no errors were added otherwise false.
1029 run_callbacks(:validate)
1033 run_callbacks(:validate_on_create)
1036 run_callbacks(:validate_on_update)
1043 # Returns the Errors object that holds all information about attribute error messages.
1045 @errors ||= Errors
.new(self)
1049 # Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
1053 # Overwrite this method for validation checks used only on creation.
1054 def validate_on_create
#:doc:
1057 # Overwrite this method for validation checks used only on updates.
1058 def validate_on_update
# :doc: