最近在处理一个小功能,每个元素可以有多个图片,每个图片的name表示了它是背景图还是海报图,
需要对每个元素的图片name做一个唯一性验证,一个元素不能添加两个海报图,
需要使用的是validates_uniqueness_of
http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_uniqueness_of
Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user can be named “davidhh”.
class Person < ActiveRecord::Base
validates_uniqueness_of :user_name
end
It can also validate whether the value of the specified attributes are unique based on a :scope
parameter:
class Person < ActiveRecord::Base
validates_uniqueness_of :user_name, scope: :account_id
end
Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.
class TeacherSchedule < ActiveRecord::Base
validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id]
end
It is also possible to limit the uniqueness constraint to a set of records matching certain conditions. In this example archived articles are not being taken into consideration when validating uniqueness of the title attribute:
class Article < ActiveRecord::Base
validates_uniqueness_of :title, conditions: -> { where.not(status: 'archived') }
end
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 attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
Configuration options:
-
:message
- Specifies a custom error message (default is: “has already been taken”). -
:scope
- One or more columns by which to limit the scope of the uniqueness constraint. -
:conditions
- Specify the conditions to be included as aWHERE
SQL fragment to limit the uniqueness constraint lookup (e.g.conditions: -> { where(status: 'active') }
). -
:case_sensitive
- Looks for an exact match. Ignored by non-text columns (true
by default). -
:allow_nil
- If set totrue
, skips this validation if the attribute isnil
(default isfalse
). -
:allow_blank
- If set totrue
, skips this validation if the attribute is blank (default isfalse
). -
:if
- Specifies a method, proc or string to call to determine if the validation should occur (e.g.if: :allow_validation
, orif: Proc.new { |user| user.signup_step > 2 }
). The method, proc or string should return or evaluate to atrue
orfalse
value. -
:unless
- Specifies a method, proc or string to call to determine if the validation should not occur (e.g.unless: :skip_validation
, orunless: Proc.new { |user| user.signup_step <= 2 }
). The method, proc or string should return or evaluate to atrue
orfalse
value.
class Picture < ApplicationRecord belongs_to :imageable, polymorphic: true validates_uniqueness_of :name, scope: [:imageable_id, :imageable_type] end