I have a validation that looks like this:
class Book < ActiveRecord::Base
belongs_to :author
validates :name, uniqueness: { scope: :author_id }
end
The problem is that I want to allow duplicate names where the author id is nil. Is there a way to do this using the validates method (and not a custom validation)?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With