ActiveRecord Validate Uniqueness with Scope Allowing Nil on Scope
Yes, with a Proc
and :unless
on the validator.
class Book < ActiveRecord::Base
belongs_to :author
validates :name, uniqueness: { scope: :author_id }, unless: Proc.new { |b| b.author_id.blank? }
end
Recommended Reading: http://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless
Make it conditional:
validates :name, uniqueness: { scope: :author_id }, if: :author_id?