Michael Irwin
Michael Irwin

Reputation: 3149

Proper way to validate uniqueness_of for multiple columns

Let's say I have this unique index on a table:

add_index :events, [:venue_id, :act_id, :occurs_on], :unique => true

Now if I want to validate this in the model, should I do this:

validates_uniqueness_of :venue_id, :scope => [:act_id, :occurs_on]

or this:

validates_uniqueness_of :venue_id, :scope => [:act_id, :occurs_on]
validates_uniqueness_of :act_id, :scope => [:venue_id, :occurs_on]
validates_uniqueness_of :occurs_on, :scope => [:venue_id, :act_id]

Upvotes: 3

Views: 1729

Answers (1)

nerdytenor
nerdytenor

Reputation: 431

Your first uniqueness constraint translates to "There can only be one of any particular venue_id, act_id, and occurs_on tuple in the table." Therefore only the first validation statement should be necessary.

Upvotes: 3

Related Questions