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
errors = @record.errors.full_messages.join(I18n.t('support.array.words_connector', :default => ', '))
14
super(I18n.t('activerecord.errors.messages.record_invalid', :errors => errors))
19
attr_accessor :base, :attribute, :type, :message, :options
21
def initialize(base, attribute, type = nil, options = {})
23
self.attribute = attribute
24
self.type = type || :invalid
25
self.options = options
26
self.message = options.delete(:message) || self.type
30
# When type is a string, it means that we do not have to do a lookup, because
31
# the user already sent the "final" message.
32
type.is_a?(String) ? type : generate_message(default_options)
36
attribute.to_s == 'base' ? message : generate_full_message(default_options)
42
@base.respond_to?(attribute) ? @base.send(attribute) : nil
47
# Translates an error message in it's default scope (<tt>activerecord.errrors.messages</tt>).
48
# Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>, if it's not there,
49
# it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not there it returns the translation of the
50
# default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name,
51
# translated attribute name and the value are available for interpolation.
53
# When using inheritence in your models, it will check all the inherited models too, but only if the model itself
54
# hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt>
55
# error +message+ for the <tt>title</tt> +attribute+, it looks for these translations:
58
# <li><tt>activerecord.errors.models.admin.attributes.title.blank</tt></li>
59
# <li><tt>activerecord.errors.models.admin.blank</tt></li>
60
# <li><tt>activerecord.errors.models.user.attributes.title.blank</tt></li>
61
# <li><tt>activerecord.errors.models.user.blank</tt></li>
62
# <li><tt>activerecord.errors.messages.blank</tt></li>
63
# <li>any default you provided through the +options+ hash (in the activerecord.errors scope)</li>
65
def generate_message(options = {})
66
keys = @base.class.self_and_descendants_from_active_record.map do |klass|
67
[ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{@message}",
68
:"models.#{klass.name.underscore}.#{@message}" ]
71
keys << options.delete(:default)
72
keys << :"messages.#{@message}"
73
keys << @message if @message.is_a?(String)
74
keys << @type unless @type == @message
77
options.merge!(:default => keys)
78
I18n.translate(keys.shift, options)
81
# Wraps an error message into a full_message format.
83
# The default full_message format for any locale is <tt>"{{attribute}} {{message}}"</tt>.
84
# One can specify locale specific default full_message format by storing it as a
85
# translation for the key <tt>:"activerecord.errors.full_messages.format"</tt>.
87
# Additionally one can specify a validation specific error message format by
88
# storing a translation for <tt>:"activerecord.errors.full_messages.[message_key]"</tt>.
89
# E.g. the full_message format for any validation that uses :blank as a message
90
# key (such as validates_presence_of) can be stored to <tt>:"activerecord.errors.full_messages.blank".</tt>
92
# Because the message key used by a validation can be overwritten on the
93
# <tt>validates_*</tt> class macro level one can customize the full_message format for
94
# any particular validation:
96
# # app/models/article.rb
97
# class Article < ActiveRecord::Base
98
# validates_presence_of :title, :message => :"title.blank"
101
# # config/locales/en.yml
107
# blank: This title is screwed!
108
def generate_full_message(options = {})
110
:"full_messages.#{@message}",
111
:'full_messages.format',
112
'{{attribute}} {{message}}'
115
options.merge!(:default => keys, :message => self.message)
116
I18n.translate(keys.shift, options)
119
# Return user options with default options.
122
options.reverse_merge :scope => [:activerecord, :errors],
123
:model => @base.class.human_name,
124
:attribute => @base.class.human_attribute_name(attribute.to_s),
129
# Active Record validation is reported to and from this object, which is used by Base#save to
130
# determine whether the object is in a valid state to be saved. See usage example in Validations.
135
def default_error_messages
136
ActiveSupport::Deprecation.warn("ActiveRecord::Errors.default_error_messages has been deprecated. Please use I18n.translate('activerecord.errors.messages').")
137
I18n.translate 'activerecord.errors.messages'
141
def initialize(base) # :nodoc:
146
# Adds an error to the base object instead of any particular attribute. This is used
147
# to report errors that don't tie to any specific attribute, but rather to the object
148
# as a whole. These error messages don't get prepended with any field name when iterating
149
# with +each_full+, so they should be complete sentences.
154
# Adds an error message (+messsage+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
155
# for the same attribute and ensure that this error object returns false when asked if <tt>empty?</tt>. More than one
156
# error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
157
# If no +messsage+ is supplied, :invalid is assumed.
158
# If +message+ is a Symbol, it will be translated, using the appropriate scope (see translate_error).
160
def add(attribute, message = nil, options = {})
161
options[:message] = options.delete(:default) if options.has_key?(:default)
162
error, message = message, nil if message.is_a?(Error)
164
@errors[attribute.to_s] ||= []
165
@errors[attribute.to_s] << (error || Error.new(@base, attribute, message, options))
168
# Will add an error message to each of the attributes in +attributes+ that is empty.
169
def add_on_empty(attributes, custom_message = nil)
170
for attr in [attributes].flatten
171
value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
172
is_empty = value.respond_to?(:empty?) ? value.empty? : false
173
add(attr, :empty, :default => custom_message) unless !value.nil? && !is_empty
177
# Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
178
def add_on_blank(attributes, custom_message = nil)
179
for attr in [attributes].flatten
180
value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
181
add(attr, :blank, :default => custom_message) if value.blank?
185
# Returns true if the specified +attribute+ has errors associated with it.
187
# class Company < ActiveRecord::Base
188
# validates_presence_of :name, :address, :email
189
# validates_length_of :name, :in => 5..30
192
# company = Company.create(:address => '123 First St.')
193
# company.errors.invalid?(:name) # => true
194
# company.errors.invalid?(:address) # => false
195
def invalid?(attribute)
196
!@errors[attribute.to_s].nil?
199
# Returns +nil+, if no errors are associated with the specified +attribute+.
200
# Returns the error message, if one error is associated with the specified +attribute+.
201
# Returns an array of error messages, if more than one error is associated with the specified +attribute+.
203
# class Company < ActiveRecord::Base
204
# validates_presence_of :name, :address, :email
205
# validates_length_of :name, :in => 5..30
208
# company = Company.create(:address => '123 First St.')
209
# company.errors.on(:name) # => ["is too short (minimum is 5 characters)", "can't be blank"]
210
# company.errors.on(:email) # => "can't be blank"
211
# company.errors.on(:address) # => nil
213
attribute = attribute.to_s
214
return nil unless @errors.has_key?(attribute)
215
errors = @errors[attribute].map(&:to_s)
216
errors.size == 1 ? errors.first : errors
221
# Returns errors assigned to the base object through +add_to_base+ according to the normal rules of <tt>on(attribute)</tt>.
226
# Yields each attribute and associated message per error added.
228
# class Company < ActiveRecord::Base
229
# validates_presence_of :name, :address, :email
230
# validates_length_of :name, :in => 5..30
233
# company = Company.create(:address => '123 First St.')
234
# company.errors.each{|attr,msg| puts "#{attr} - #{msg}" }
235
# # => name - is too short (minimum is 5 characters)
236
# # name - can't be blank
237
# # address - can't be blank
239
@errors.each_key { |attr| @errors[attr].each { |error| yield attr, error.message } }
243
@errors.each_key { |attr| @errors[attr].each { |error| yield attr, error } }
246
# Yields each full error message added. So <tt>Person.errors.add("first_name", "can't be empty")</tt> will be returned
247
# through iteration as "First name can't be empty".
249
# class Company < ActiveRecord::Base
250
# validates_presence_of :name, :address, :email
251
# validates_length_of :name, :in => 5..30
254
# company = Company.create(:address => '123 First St.')
255
# company.errors.each_full{|msg| puts msg }
256
# # => Name is too short (minimum is 5 characters)
257
# # Name can't be blank
258
# # Address can't be blank
260
full_messages.each { |msg| yield msg }
263
# Returns all the full error messages in an array.
265
# class Company < ActiveRecord::Base
266
# validates_presence_of :name, :address, :email
267
# validates_length_of :name, :in => 5..30
270
# company = Company.create(:address => '123 First St.')
271
# company.errors.full_messages # =>
272
# ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
273
def full_messages(options = {})
274
@errors.values.inject([]) do |full_messages, errors|
275
full_messages + errors.map { |error| error.full_message }
279
# Returns true if no errors have been added.
284
# Removes all errors that have been added.
286
@errors = ActiveSupport::OrderedHash.new
289
# Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
291
@errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
294
alias_method :count, :size
295
alias_method :length, :size
297
# Returns an XML representation of this error object.
299
# class Company < ActiveRecord::Base
300
# validates_presence_of :name, :address, :email
301
# validates_length_of :name, :in => 5..30
304
# company = Company.create(:address => '123 First St.')
305
# company.errors.to_xml
306
# # => <?xml version="1.0" encoding="UTF-8"?>
308
# # <error>Name is too short (minimum is 5 characters)</error>
309
# # <error>Name can't be blank</error>
310
# # <error>Address can't be blank</error>
312
def to_xml(options={})
313
options[:root] ||= "errors"
314
options[:indent] ||= 2
315
options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
317
options[:builder].instruct! unless options.delete(:skip_instruct)
318
options[:builder].errors do |e|
319
full_messages.each { |msg| e.error(msg) }
323
def generate_message(attribute, message = :invalid, options = {})
324
ActiveSupport::Deprecation.warn("ActiveRecord::Errors#generate_message has been deprecated. Please use ActiveRecord::Error.new().to_s.")
325
Error.new(@base, attribute, message, options).to_s
330
# Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
332
# Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
333
# +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
334
# that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
338
# class Person < ActiveRecord::Base
341
# errors.add_on_empty %w( first_name last_name )
342
# errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
345
# def validate_on_create # is only run the first time a new object is saved
346
# unless valid_discount?(membership_discount)
347
# errors.add("membership_discount", "has expired")
351
# def validate_on_update
352
# errors.add_to_base("No changes have occurred") if unchanged_attributes?
356
# person = Person.new("first_name" => "David", "phone_number" => "what?")
357
# person.save # => false (and doesn't do the save)
358
# person.errors.empty? # => false
359
# person.errors.count # => 2
360
# person.errors.on "last_name" # => "can't be empty"
361
# person.errors.on "phone_number" # => "has invalid format"
362
# person.errors.each_full { |msg| puts msg }
363
# # => "Last name can't be empty\n" +
364
# # "Phone number has invalid format"
366
# person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
367
# person.save # => true (and person is now saved in the database)
369
# An Errors object is automatically created for every Active Record.
371
VALIDATIONS = %w( validate validate_on_create validate_on_update )
373
def self.included(base) # :nodoc:
374
base.extend ClassMethods
376
alias_method_chain :save, :validation
377
alias_method_chain :save!, :validation
380
base.send :include, ActiveSupport::Callbacks
381
base.define_callbacks *VALIDATIONS
384
# Active Record classes can implement validations in several ways. The highest level, easiest to read,
385
# and recommended approach is to use the declarative <tt>validates_..._of</tt> class methods (and
386
# +validates_associated+) documented below. These are sufficient for most model validations.
388
# Slightly lower level is +validates_each+. It provides some of the same options as the purely declarative
389
# validation methods, but like all the lower-level approaches it requires manually adding to the errors collection
390
# when the record is invalid.
392
# At a yet lower level, a model can use the class methods +validate+, +validate_on_create+ and +validate_on_update+
393
# to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance
396
# The lowest level style is to define the instance methods +validate+, +validate_on_create+ and +validate_on_update+
397
# as documented in ActiveRecord::Validations.
399
# == +validate+, +validate_on_create+ and +validate_on_update+ Class Methods
401
# Calls to these methods add a validation method or block to the class. Again, this approach is recommended
402
# only when the higher-level methods documented below (<tt>validates_..._of</tt> and +validates_associated+) are
403
# insufficient to handle the required validation.
405
# This can be done with a symbol pointing to a method:
407
# class Comment < ActiveRecord::Base
408
# validate :must_be_friends
410
# def must_be_friends
411
# errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
415
# Or with a block which is passed the current record to be validated:
417
# class Comment < ActiveRecord::Base
418
# validate do |comment|
419
# comment.must_be_friends
422
# def must_be_friends
423
# errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
427
# This usage applies to +validate_on_create+ and +validate_on_update+ as well.
429
DEFAULT_VALIDATION_OPTIONS = {
432
:allow_blank => false,
436
ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
437
ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=',
438
:equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
439
:odd => 'odd?', :even => 'even?' }.freeze
441
# Validates each attribute against a block.
443
# class Person < ActiveRecord::Base
444
# validates_each :first_name, :last_name do |record, attr, value|
445
# record.errors.add attr, 'starts with z.' if value[0] == ?z
450
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
451
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
452
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
453
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
454
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
455
# method, proc or string should return or evaluate to a true or false value.
456
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
457
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
458
# method, proc or string should return or evaluate to a true or false value.
459
def validates_each(*attrs)
460
options = attrs.extract_options!.symbolize_keys
461
attrs = attrs.flatten
463
# Declare the validation.
464
send(validation_method(options[:on] || :save), options) do |record|
466
value = record.send(attr)
467
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
468
yield record, attr, value
473
# Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
476
# class Person < ActiveRecord::Base
477
# validates_confirmation_of :user_name, :password
478
# validates_confirmation_of :email_address, :message => "should match confirmation"
482
# <%= password_field "person", "password" %>
483
# <%= password_field "person", "password_confirmation" %>
485
# The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
486
# To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
487
# only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
488
# check for the confirmation attribute:
490
# validates_presence_of :password_confirmation, :if => :password_changed?
492
# Configuration options:
493
# * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation").
494
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
495
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
496
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
497
# method, proc or string should return or evaluate to a true or false value.
498
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
499
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
500
# method, proc or string should return or evaluate to a true or false value.
501
def validates_confirmation_of(*attr_names)
502
configuration = { :on => :save }
503
configuration.update(attr_names.extract_options!)
505
attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" }))
507
validates_each(attr_names, configuration) do |record, attr_name, value|
508
unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
509
record.errors.add(attr_name, :confirmation, :default => configuration[:message])
514
# Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
516
# class Person < ActiveRecord::Base
517
# validates_acceptance_of :terms_of_service
518
# validates_acceptance_of :eula, :message => "must be abided"
521
# If the database column does not exist, the +terms_of_service+ attribute is entirely virtual. This check is
522
# performed only if +terms_of_service+ is not +nil+ and by default on save.
524
# Configuration options:
525
# * <tt>:message</tt> - A custom error message (default is: "must be accepted").
526
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
527
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is true).
528
# * <tt>:accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
529
# makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
530
# column, since the attribute is typecast from "1" to +true+ before validation.
531
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
532
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
533
# method, proc or string should return or evaluate to a true or false value.
534
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
535
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
536
# method, proc or string should return or evaluate to a true or false value.
537
def validates_acceptance_of(*attr_names)
538
configuration = { :on => :save, :allow_nil => true, :accept => "1" }
539
configuration.update(attr_names.extract_options!)
543
rescue Exception # To ignore both statement and connection errors
546
names = attr_names.reject { |name| db_cols.include?(name.to_s) }
547
attr_accessor(*names)
549
validates_each(attr_names,configuration) do |record, attr_name, value|
550
unless value == configuration[:accept]
551
record.errors.add(attr_name, :accepted, :default => configuration[:message])
556
# Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
558
# class Person < ActiveRecord::Base
559
# validates_presence_of :first_name
562
# The first_name attribute must be in the object and it cannot be blank.
564
# If you want to validate the presence of a boolean field (where the real values are true and false),
565
# you will want to use <tt>validates_inclusion_of :field_name, :in => [true, false]</tt>.
567
# This is due to the way Object#blank? handles boolean values: <tt>false.blank? # => true</tt>.
569
# Configuration options:
570
# * <tt>message</tt> - A custom error message (default is: "can't be blank").
571
# * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>,
573
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
574
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
575
# The method, proc or string should return or evaluate to a true or false value.
576
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
577
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
578
# The method, proc or string should return or evaluate to a true or false value.
580
def validates_presence_of(*attr_names)
581
configuration = { :on => :save }
582
configuration.update(attr_names.extract_options!)
584
# can't use validates_each here, because it cannot cope with nonexistent attributes,
585
# while errors.add_on_empty can
586
send(validation_method(configuration[:on]), configuration) do |record|
587
record.errors.add_on_blank(attr_names, configuration[:message])
591
# Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
593
# class Person < ActiveRecord::Base
594
# validates_length_of :first_name, :maximum=>30
595
# validates_length_of :last_name, :maximum=>30, :message=>"less than {{count}} if you don't mind"
596
# validates_length_of :fax, :in => 7..32, :allow_nil => true
597
# validates_length_of :phone, :in => 7..32, :allow_blank => true
598
# validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
599
# validates_length_of :fav_bra_size, :minimum => 1, :too_short => "please enter at least {{count}} character"
600
# validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with {{count}} characters... don't play me."
601
# validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least {{count}} words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
604
# Configuration options:
605
# * <tt>:minimum</tt> - The minimum size of the attribute.
606
# * <tt>:maximum</tt> - The maximum size of the attribute.
607
# * <tt>:is</tt> - The exact size of the attribute.
608
# * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
609
# * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
610
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
611
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
612
# * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is {{count}} characters)").
613
# * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is {{count}} characters)").
614
# * <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)").
615
# * <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.
616
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
617
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
618
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
619
# method, proc or string should return or evaluate to a true or false value.
620
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
621
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
622
# method, proc or string should return or evaluate to a true or false value.
623
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
624
# count words as in above example.)
625
# Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
626
def validates_length_of(*attrs)
627
# Merge given options with defaults.
629
:tokenizer => lambda {|value| value.split(//)}
630
}.merge(DEFAULT_VALIDATION_OPTIONS)
631
options.update(attrs.extract_options!.symbolize_keys)
633
# Ensure that one and only one range option is specified.
634
range_options = ALL_RANGE_OPTIONS & options.keys
635
case range_options.size
637
raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
639
# Valid number of options; do nothing.
641
raise ArgumentError, 'Too many range options specified. Choose only one.'
644
# Get range option and value.
645
option = range_options.first
646
option_value = options[range_options.first]
647
key = {:is => :wrong_length, :minimum => :too_short, :maximum => :too_long}[option]
648
custom_message = options[:message] || options[key]
652
raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)
654
validates_each(attrs, options) do |record, attr, value|
655
value = options[:tokenizer].call(value) if value.kind_of?(String)
656
if value.nil? or value.size < option_value.begin
657
record.errors.add(attr, :too_short, :default => custom_message || options[:too_short], :count => option_value.begin)
658
elsif value.size > option_value.end
659
record.errors.add(attr, :too_long, :default => custom_message || options[:too_long], :count => option_value.end)
662
when :is, :minimum, :maximum
663
raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
665
# Declare different validations per option.
666
validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
668
validates_each(attrs, options) do |record, attr, value|
669
value = options[:tokenizer].call(value) if value.kind_of?(String)
670
unless !value.nil? and value.size.method(validity_checks[option])[option_value]
671
record.errors.add(attr, key, :default => custom_message, :count => option_value)
677
alias_method :validates_size_of, :validates_length_of
680
# Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
681
# can be named "davidhh".
683
# class Person < ActiveRecord::Base
684
# validates_uniqueness_of :user_name, :scope => :account_id
687
# It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example,
688
# making sure that a teacher can only be on the schedule once per semester for a particular class.
690
# class TeacherSchedule < ActiveRecord::Base
691
# validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
694
# 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
695
# attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
697
# Configuration options:
698
# * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
699
# * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
700
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default).
701
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
702
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
703
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
704
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
705
# method, proc or string should return or evaluate to a true or false value.
706
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
707
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
708
# method, proc or string should return or evaluate to a true or false value.
710
# === Concurrency and integrity
712
# Using this validation method in conjunction with ActiveRecord::Base#save
713
# does not guarantee the absence of duplicate record insertions, because
714
# uniqueness checks on the application level are inherently prone to race
715
# conditions. For example, suppose that two users try to post a Comment at
716
# the same time, and a Comment's title must be unique. At the database-level,
717
# the actions performed by these users could be interleaved in the following manner:
720
# ------------------------------------+--------------------------------------
721
# # User 1 checks whether there's |
722
# # already a comment with the title |
723
# # 'My Post'. This is not the case. |
724
# SELECT * FROM comments |
725
# WHERE title = 'My Post' |
727
# | # User 2 does the same thing and also
728
# | # infers that his title is unique.
729
# | SELECT * FROM comments
730
# | WHERE title = 'My Post'
732
# # User 1 inserts his comment. |
733
# INSERT INTO comments |
734
# (title, content) VALUES |
735
# ('My Post', 'hi!') |
737
# | # User 2 does the same thing.
738
# | INSERT INTO comments
739
# | (title, content) VALUES
740
# | ('My Post', 'hello!')
743
# | # Boom! We now have a duplicate
746
# This could even happen if you use transactions with the 'serializable'
747
# isolation level. There are several ways to get around this problem:
748
# - By locking the database table before validating, and unlocking it after
749
# saving. However, table locking is very expensive, and thus not
751
# - By locking a lock file before validating, and unlocking it after saving.
752
# This does not work if you've scaled your Rails application across
753
# multiple web servers (because they cannot share lock files, or cannot
754
# do that efficiently), and thus not recommended.
755
# - Creating a unique index on the field, by using
756
# ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
757
# rare case that a race condition occurs, the database will guarantee
758
# the field's uniqueness.
760
# When the database catches such a duplicate insertion,
761
# ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
762
# exception. You can either choose to let this error propagate (which
763
# will result in the default Rails exception page being shown), or you
764
# can catch it and restart the transaction (e.g. by telling the user
765
# that the title already exists, and asking him to re-enter the title).
766
# This technique is also known as optimistic concurrency control:
767
# http://en.wikipedia.org/wiki/Optimistic_concurrency_control
769
# Active Record currently provides no way to distinguish unique
770
# index constraint errors from other types of database errors, so you
771
# will have to parse the (database-specific) exception message to detect
773
def validates_uniqueness_of(*attr_names)
774
configuration = { :case_sensitive => true }
775
configuration.update(attr_names.extract_options!)
777
validates_each(attr_names,configuration) do |record, attr_name, value|
778
# The check for an existing value should be run from a class that
779
# isn't abstract. This means working down from the current class
780
# (self), to the first non-abstract class. Since classes don't know
781
# their subclasses, we have to build the hierarchy between self and
782
# the record's class.
783
class_hierarchy = [record.class]
784
while class_hierarchy.first != self
785
class_hierarchy.insert(0, class_hierarchy.first.superclass)
788
# Now we can work our way down the tree to the first non-abstract
789
# class (which has a database table to query from).
790
finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }
792
column = finder_class.columns_hash[attr_name.to_s]
795
comparison_operator = "IS ?"
797
comparison_operator = "#{connection.case_sensitive_equality_operator} ?"
798
value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s
800
comparison_operator = "= ?"
803
sql_attribute = "#{record.class.quoted_table_name}.#{connection.quote_column_name(attr_name)}"
805
if value.nil? || (configuration[:case_sensitive] || !column.text?)
806
condition_sql = "#{sql_attribute} #{comparison_operator}"
807
condition_params = [value]
809
condition_sql = "LOWER(#{sql_attribute}) #{comparison_operator}"
810
condition_params = [value.mb_chars.downcase]
813
if scope = configuration[:scope]
814
Array(scope).map do |scope_item|
815
scope_value = record.send(scope_item)
816
condition_sql << " AND " << attribute_condition("#{record.class.quoted_table_name}.#{scope_item}", scope_value)
817
condition_params << scope_value
821
unless record.new_record?
822
condition_sql << " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?"
823
condition_params << record.send(:id)
826
finder_class.with_exclusive_scope do
827
if finder_class.exists?([condition_sql, *condition_params])
828
record.errors.add(attr_name, :taken, :default => configuration[:message], :value => value)
835
# Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
838
# class Person < ActiveRecord::Base
839
# validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
842
# 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.
844
# A regular expression must be provided or else an exception will be raised.
846
# Configuration options:
847
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
848
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
849
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
850
# * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!).
851
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
852
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
853
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => 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
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
856
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
857
# method, proc or string should return or evaluate to a true or false value.
858
def validates_format_of(*attr_names)
859
configuration = { :on => :save, :with => nil }
860
configuration.update(attr_names.extract_options!)
862
raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
864
validates_each(attr_names, configuration) do |record, attr_name, value|
865
unless value.to_s =~ configuration[:with]
866
record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
871
# Validates whether the value of the specified attribute is available in a particular enumerable object.
873
# class Person < ActiveRecord::Base
874
# validates_inclusion_of :gender, :in => %w( m f )
875
# validates_inclusion_of :age, :in => 0..99
876
# validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension {{value}} is not included in the list"
879
# Configuration options:
880
# * <tt>:in</tt> - An enumerable object of available items.
881
# * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
882
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
883
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
884
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
885
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
886
# method, proc or string should return or evaluate to a true or false value.
887
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
888
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
889
# method, proc or string should return or evaluate to a true or false value.
890
def validates_inclusion_of(*attr_names)
891
configuration = { :on => :save }
892
configuration.update(attr_names.extract_options!)
894
enum = configuration[:in] || configuration[:within]
896
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?)
898
validates_each(attr_names, configuration) do |record, attr_name, value|
899
unless enum.include?(value)
900
record.errors.add(attr_name, :inclusion, :default => configuration[:message], :value => value)
905
# Validates that the value of the specified attribute is not in a particular enumerable object.
907
# class Person < ActiveRecord::Base
908
# validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
909
# validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
910
# validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension {{value}} is not allowed"
913
# Configuration options:
914
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
915
# * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
916
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
917
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
918
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
919
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
920
# method, proc or string should return or evaluate to a true or false value.
921
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
922
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
923
# method, proc or string should return or evaluate to a true or false value.
924
def validates_exclusion_of(*attr_names)
925
configuration = { :on => :save }
926
configuration.update(attr_names.extract_options!)
928
enum = configuration[:in] || configuration[:within]
930
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?)
932
validates_each(attr_names, configuration) do |record, attr_name, value|
933
if enum.include?(value)
934
record.errors.add(attr_name, :exclusion, :default => configuration[:message], :value => value)
939
# Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
941
# class Book < ActiveRecord::Base
943
# belongs_to :library
945
# validates_associated :pages, :library
948
# Warning: If, after the above definition, you then wrote:
950
# class Page < ActiveRecord::Base
953
# validates_associated :book
956
# this would specify a circular dependency and cause infinite recursion.
958
# NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
959
# is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
961
# Configuration options:
962
# * <tt>:message</tt> - A custom error message (default is: "is invalid")
963
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
964
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
965
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
966
# method, proc or string should return or evaluate to a true or false value.
967
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
968
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
969
# method, proc or string should return or evaluate to a true or false value.
970
def validates_associated(*attr_names)
971
configuration = { :on => :save }
972
configuration.update(attr_names.extract_options!)
974
validates_each(attr_names, configuration) do |record, attr_name, value|
975
unless (value.is_a?(Array) ? value : [value]).collect { |r| r.nil? || r.valid? }.all?
976
record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
981
# Validates whether the value of the specified attribute is numeric by trying to convert it to
982
# a float with Kernel.Float (if <tt>only_integer</tt> is false) or applying it to the regular expression
983
# <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>only_integer</tt> is set to true).
985
# class Person < ActiveRecord::Base
986
# validates_numericality_of :value, :on => :create
989
# Configuration options:
990
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
991
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
992
# * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
993
# * <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+.
994
# * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
995
# * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value.
996
# * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
997
# * <tt>:less_than</tt> - Specifies the value must be less than the supplied value.
998
# * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value.
999
# * <tt>:odd</tt> - Specifies the value must be an odd number.
1000
# * <tt>:even</tt> - Specifies the value must be an even number.
1001
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
1002
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
1003
# method, proc or string should return or evaluate to a true or false value.
1004
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
1005
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
1006
# method, proc or string should return or evaluate to a true or false value.
1007
def validates_numericality_of(*attr_names)
1008
configuration = { :on => :save, :only_integer => false, :allow_nil => false }
1009
configuration.update(attr_names.extract_options!)
1012
numericality_options = ALL_NUMERICALITY_CHECKS.keys & configuration.keys
1014
(numericality_options - [ :odd, :even ]).each do |option|
1015
raise ArgumentError, ":#{option} must be a number" unless configuration[option].is_a?(Numeric)
1018
validates_each(attr_names,configuration) do |record, attr_name, value|
1019
raw_value = record.send("#{attr_name}_before_type_cast") || value
1021
next if configuration[:allow_nil] and raw_value.nil?
1023
if configuration[:only_integer]
1024
unless raw_value.to_s =~ /\A[+-]?\d+\Z/
1025
record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
1028
raw_value = raw_value.to_i
1031
raw_value = Kernel.Float(raw_value)
1032
rescue ArgumentError, TypeError
1033
record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
1038
numericality_options.each do |option|
1041
unless raw_value.to_i.method(ALL_NUMERICALITY_CHECKS[option])[]
1042
record.errors.add(attr_name, option, :value => raw_value, :default => configuration[:message])
1045
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]]
1051
# Creates an object just like Base.create but calls save! instead of save
1052
# so an exception is raised if the record is invalid.
1053
def create!(attributes = nil, &block)
1054
if attributes.is_a?(Array)
1055
attributes.collect { |attr| create!(attr, &block) }
1057
object = new(attributes)
1058
yield(object) if block_given?
1065
def validation_method(on)
1067
when :save then :validate
1068
when :create then :validate_on_create
1069
when :update then :validate_on_update
1074
# The validation process on save can be skipped by passing false. The regular Base#save method is
1075
# replaced with this when the validations module is mixed in, which it is by default.
1076
def save_with_validation(perform_validation = true)
1077
if perform_validation && valid? || !perform_validation
1078
save_without_validation
1084
# Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
1085
# if the record is not valid.
1086
def save_with_validation!
1088
save_without_validation!
1090
raise RecordInvalid.new(self)
1094
# Runs +validate+ and +validate_on_create+ or +validate_on_update+ and returns true if no errors were added otherwise false.
1098
run_callbacks(:validate)
1102
run_callbacks(:validate_on_create)
1105
run_callbacks(:validate_on_update)
1112
# Performs the opposite of <tt>valid?</tt>. Returns true if errors were added, false otherwise.
1117
# Returns the Errors object that holds all information about attribute error messages.
1119
@errors ||= Errors.new(self)
1123
# Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
1127
# Overwrite this method for validation checks used only on creation.
1128
def validate_on_create
1131
# Overwrite this method for validation checks used only on updates.
1132
def validate_on_update