次のような検証があります。
class Book < ActiveRecord::Base
belongs_to :author
validates :name, uniqueness: { scope: :author_id }
end
問題は、著者 ID が nil である重複した名前を許可したいということです。validates メソッドを使用してこれを行う方法はありますか (カスタム検証ではありません)?
次のような検証があります。
class Book < ActiveRecord::Base
belongs_to :author
validates :name, uniqueness: { scope: :author_id }
end
問題は、著者 ID が nil である重複した名前を許可したいということです。validates メソッドを使用してこれを行う方法はありますか (カスタム検証ではありません)?
はい。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