RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

How can I use validations in Rails 3.1 to enforce composite uniqueness?

I have a Customer model that belongs_to Brand. Customer has only name and identifier (a string) as attributes. I want to enforce the uniqueness of name and identifier only within a particular brand. How can I enforce that scoped uniqueness?

Upvotes: 5

Views: 1087

Answers (1)

John Feminella
John Feminella

Reputation: 311755

Use the :scope parameter of the ActiveRecord::Validations#validates_uniqueness_of validation:

validates_uniqueness_of :brand_id, :scope => [:name, :identifier]

Alternately:

validates :brand_id, :uniqueness => {:scope => [:name, :identifer]}

Either way, this says, "for a given name and identifier, the brand_id must be unique".

Upvotes: 13

Related Questions