您可以通过将要执行的简单 Ruby 字符串、Proc 或方法名称作为值作为值传递给验证选项中的 :if 或 :unless 来使验证成为条件。以下是一些示例:
在 Rails 5.2 版本之前,您可以传递一个字符串:
# using a string:
validates :name, uniqueness: true, if: 'name.present?'
从 5.2 开始,不再支持字符串,为您提供以下选项:
# using a Proc:
validates :email, presence: true, if: Proc.new { |user| user.approved? }
# using a Lambda (a type of proc ... and a good replacement for deprecated strings):
validates :email, presence: true, if: -> { name.present? }
# using a symbol to call a method:
validates :address, presence: true, if: :some_complex_condition
def some_complex_condition
true # do your checking and return true or false
end
在你的情况下,你可以这样做:
class Question < ActiveRecord::Base
attr_accessible :user_id, :created_on
validates_uniqueness_of :created_on, :scope => :user_id, unless: Proc.new { |question| question.user.is_admin? }
end
有关详细信息,请查看 rails 指南上的条件验证部分:http://edgeguides.rubyonrails.org/active_record_validations.html#conditional-validation