module ActiveRecord::Validations::ClassMethods
def create!(attributes = nil, &block)
Creates an object just like Base.create but calls save! instead of +save+
def create!(attributes = nil, &block) if attributes.is_a?(Array) attributes.collect { |attr| create!(attr, &block) } else object = new(attributes) yield(object) if block_given? object.save! object end end
def validates_associated(*attr_names)
method, proc or string should return or evaluate to a +true+ or +false+
or unless: Proc.new { |user| user.signup_step <= 2 }). The
determine if the validation should not occur (e.g. unless: :skip_validation,
* :unless - Specifies a method, proc or string to call to
proc or string should return or evaluate to a +true+ or +false+ value.
or if: Proc.new { |user| user.signup_step > 2 }). The method,
if the validation should occur (e.g. if: :allow_validation,
* :if - Specifies a method, proc or string to call to determine
and :update.
validation contexts by default (+nil+), other options are :create
* :on - Specifies when this validation is active. Runs in all
* :message - A custom error message (default is: "is invalid").
Configuration options:
guaranteed to be valid, you also need to use +validates_presence_of+.
assigned. If you want to ensure that the association is both present and
NOTE: This validation will not fail if the association hasn't been
Doing so will lead to a circular dependency and cause infinite recursion.
WARNING: This validation must not be used on both ends of an association.
end
validates_associated :pages, :library
belongs_to :library
has_many :pages
class Book < ActiveRecord::Base
Works with any kind of association.
Validates whether the associated object or objects are all valid.
def validates_associated(*attr_names) validates_with AssociatedValidator, _merge_attributes(attr_names) end
def validates_presence_of(*attr_names)
* :strict - Specifies whether validation should be strict.
proc or string should return or evaluate to a +true+ or +false+ value.
or unless: Proc.new { |user| user.signup_step <= 2 }). The method,
if the validation should not occur (e.g. unless: :skip_validation,
* :unless - Specifies a method, proc or string to call to determine
or string should return or evaluate to a +true+ or +false+ value.
if: Proc.new { |user| user.signup_step > 2 }). The method, proc
the validation should occur (e.g. if: :allow_validation, or
* :if - Specifies a method, proc or string to call to determine if
and :update.
validation contexts by default (+nil+), other options are :create
* :on - Specifies when this validation is active. Runs in all
* :message - A custom error message (default is: "can't be blank").
Configuration options:
state.
deletes the associated object, thus putting the parent object into an invalid
prevents the parent object from validating successfully and saving, which then
check to see that an associated object is not marked for destruction. This
This validator defers to the ActiveModel validation for presence, adding the
false.blank? # => true.
This is due to the way Object#blank? handles boolean values:
validates_inclusion_of :field_name, in: [true, false].
are true and false), you will want to use
If you want to validate the presence of a boolean field (where the real values
for destruction.
The face attribute must be in the object and it cannot be blank or marked
end
validates_presence_of :face
has_one :face
class Person < ActiveRecord::Base
on save.
associated object is not marked for destruction. Happens by default
Object#blank?), and, if the attribute is an association, that the
Validates that the specified attributes are not blank (as defined by
def validates_presence_of(*attr_names) validates_with PresenceValidator, _merge_attributes(attr_names) end
def validates_uniqueness_of(*attr_names)
* ActiveRecord::ConnectionAdapters::SQLite3Adapter.
* ActiveRecord::ConnectionAdapters::Mysql2Adapter.
* ActiveRecord::ConnectionAdapters::MysqlAdapter.
The following bundled adapters throw the ActiveRecord::RecordNotUnique exception:
a case.
have to parse the (database-specific) exception message to detect such
ActiveRecord::RecordNotUnique exception. For other adapters you will
constraint errors from other types of database errors by throwing an
The bundled ActiveRecord::ConnectionAdapters distinguish unique index
{optimistic concurrency control}[http://en.wikipedia.org/wiki/Optimistic_concurrency_control].
This technique is also known as
that the title already exists, and asking him to re-enter the title).
can catch it and restart the transaction (e.g. by telling the user
will result in the default Rails exception page being shown), or you
exception. You can either choose to let this error propagate (which
ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
When the database catches such a duplicate insertion,
the field's uniqueness.
rare case that a race condition occurs, the database will guarantee
ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
index to the database table using
isolation level. The best way to work around this problem is to add a unique
This could even happen if you use transactions with the 'serializable'
| # title!
| # Boom! We now have a duplicate
| # ^^^^^^
|
| ('My Post', 'hello!')
| (title, content) VALUES
| INSERT INTO comments
| # User 2 does the same thing.
|
('My Post', 'hi!') |
(title, content) VALUES |
INSERT INTO comments |
# User 1 inserts his comment. |
|
| WHERE title = 'My Post'
| SELECT * FROM comments
| # infers that his title is unique.
| # User 2 does the same thing and also
|
WHERE title = 'My Post' |
SELECT * FROM comments |
# 'My Post'. This is not the case. |
# already a comment with the title |
# User 1 checks whether there's |
------------------------------------+--------------------------------------
User 1 | User 2
the actions performed by these users could be interleaved in the following manner:
the same time, and a Comment's title must be unique. At the database-level,
conditions. For example, suppose that two users try to post a Comment at
uniqueness checks on the application level are inherently prone to race
does not guarantee the absence of duplicate record insertions, because
Using this validation method in conjunction with ActiveRecord::Base#save
=== Concurrency and integrity
value.
method, proc or string should return or evaluate to a +true+ or +false+
or unless: Proc.new { |user| user.signup_step <= 2 }). The
determine if the validation should ot occur (e.g. unless: :skip_validation,
* :unless - Specifies a method, proc or string to call to
proc or string should return or evaluate to a +true+ or +false+ value.
or if: Proc.new { |user| user.signup_step > 2 }). The method,
if the validation should occur (e.g. if: :allow_validation,
* :if - Specifies a method, proc or string to call to determine
attribute is blank (default is +false+).
* :allow_blank - If set to +true+, skips this validation if the
attribute is +nil+ (default is +false+).
* :allow_nil - If set to +true+, skips this validation if the
non-text columns (+true+ by default).
* :case_sensitive - Looks for an exact match. Ignored by
(e.g. conditions: -> { where(status: 'active') }).
WHERE SQL fragment to limit the uniqueness constraint lookup
* :conditions - Specify the conditions to be included as a
the uniqueness constraint.
* :scope - One or more columns by which to limit the scope of
"has already been taken").
* :message - Specifies a custom error message (default is:
Configuration options:
the same check is made but disregarding the record itself.
attribute (that maps to a column). When the record is updated,
record exists in the database with the given value for the specified
When the record is created, a check is performed to make sure that no
end
validates_uniqueness_of :title, conditions: -> { where.not(status: 'archived') }
class Article < ActiveRecord::Base
of the title attribute:
are not being taken into consideration when validating uniqueness
records matching certain conditions. In this example archived articles
It is also possible to limit the uniqueness constraint to a set of
end
validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id]
class TeacherSchedule < ActiveRecord::Base
class.
teacher can only be on the schedule once per semester for a particular
Or even multiple scope parameters. For example, making sure that a
end
validates_uniqueness_of :user_name, scope: :account_id
class Person < ActiveRecord::Base
unique based on a :scope parameter:
It can also validate whether the value of the specified attributes are
end
validates_uniqueness_of :user_name
class Person < ActiveRecord::Base
can be named "davidhh".
across the system. Useful for making sure that only one user
Validates whether the value of the specified attributes are unique
def validates_uniqueness_of(*attr_names) validates_with UniquenessValidator, _merge_attributes(attr_names) end