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

Mar*_*ser 22 activerecord ruby-on-rails

我有一个看起来像这样的验证:

class Book < ActiveRecord::Base

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

end
Run Code Online (Sandbox Code Playgroud)

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

dee*_*our 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
Run Code Online (Sandbox Code Playgroud)

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


gro*_*ser 5

Make it conditional:

  validates :name, uniqueness: { scope: :author_id }, if: :author_id?
Run Code Online (Sandbox Code Playgroud)