Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 518
AKWF Avatar asked Feb 14 '12 23:02

AKWF


1 Answers

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".

like image 51
John Feminella Avatar answered Dec 02 '22 17:12

John Feminella