Rails 3 validate uniqueness of one value against a column?

Viewed 10454

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?

6 Answers

Using @raj answer with validates method:

validates(
    :company_id,
    uniqueness: { conditions: -> { where(active: true) } }
  )
Related