ActiveRecord使用范围验证唯一性允许范围为零

时间:2012-12-15 03:55:41

标签: ruby-on-rails activerecord

我的验证看起来像这样:

class Book < ActiveRecord::Base

  belongs_to :author
  validates :name, uniqueness: { scope: :author_id }

end

问题是我想允许作者id为nil的重复名称。有没有办法使用validates方法(而不是自定义验证)?

3 个答案:

答案 0 :(得分:26)

是的,验证工具上有Proc:unless

class Book < ActiveRecord::Base

  belongs_to :author
  validates :name, uniqueness: { scope: :author_id }, unless: Proc.new { |b| b.author_id.blank? }

end

推荐阅读: http://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless

答案 1 :(得分:0)

让它成为条件:

  validates :name, uniqueness: { scope: :author_id }, if: :author_id?

答案 2 :(得分:0)

如果您希望语法更加简洁,则上述带有Proc的答案也可以使用Lambda编写,以达到相同的效果,如下所示。

class Book < ActiveRecord::Base

  belongs_to :author
  validates :name, uniqueness: { scope: :author_id }, unless: -> { |b| b.author_id.blank? }

end