Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 validate uniqueness of one value against a column?

I have a model with an active column, which is a boolean. I want to validate the uniqueness of all newly added records against company_id, such that I can add as many records as I want with the same company_id to the table so long as active is set to false. There should only be one active record for each company_id.

How would I write this? I've already tried:

validates :company_id, :uniqueness => { :scope => :active }

But that seems to also validate against unique combinations of active being false (such that I can never have more than two company_id's in the table with the same active status, regardless of what active is)--the validation above allows two records for company_id, one with active = false and the other with active = true. Once those two records are in, the validation blocks everything else.

I then tried adding this:

scope :active, where(:active => true)

But that doesn't seem to have changed the validation at all (same issue as above).

How can I write this validation so that I can add as many records with the same company_id so long as active is false, and only allowing one active = true per company_id?

like image 942
neezer Avatar asked Aug 09 '11 22:08

neezer


1 Answers

No need to use validates_each - that's only if you want to pass multiple attributes through the same block. Just create a custom validation:

validate :company_id_when_active

def company_id_when_active
  if active? and CompanyTerm.exists? ["company_id = ? AND active = 1 AND id != ?", company_id, id.to_i]
    errors.add( :company_id, 'already has an active term')
  end
end
like image 145
smathy Avatar answered Nov 11 '22 19:11

smathy