Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord Validate Uniqueness with Scope Allowing Nil on Scope

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)?

like image 698
Mark Fraser Avatar asked Dec 15 '12 03:12

Mark Fraser


2 Answers

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

like image 177
deefour Avatar answered Nov 15 '22 20:11

deefour


Make it conditional:

  validates :name, uniqueness: { scope: :author_id }, if: :author_id?
like image 24
grosser Avatar answered Nov 15 '22 20:11

grosser