26

次のような検証があります。

class Book < ActiveRecord::Base

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

end

問題は、著者 ID が nil である重複した名前を許可したいということです。validates メソッドを使用してこれを行う方法はありますか (カスタム検証ではありません)?

4

2 に答える 2

30

はい。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

于 2012-12-15T04:01:27.113 に答える