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

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


Make it conditional:

  validates :name, uniqueness: { scope: :author_id }, if: :author_id?

Need Your Help

Does the ternary operator exist in R?

r operators

As the question asks, is there a control sequence in R similar to C's ternary operator? If so, how do you use it? Thanks!

NSURLConnection doesn't call delegate methods

iphone delegates nsurlconnection

I saw similar questions here, but I couldn't find solution to my problem.