johan
johan

Reputation: 2329

How to validate uniqueness in Rails 3 Model if I want to check if there is a 2-field combination?

I want to know if there is a way in Rails 3, in which I can validate the uniqueness of 2 fields that goes in combination.

The logic goes this way:

I have two fields employee_code and date_entry.

Upvotes: 15

Views: 13024

Answers (2)

johan
johan

Reputation: 2329

This is for Rails 3:

To do this with just 2 columns, you can just do something like:

validates :empcode, :uniqueness => {:scope => :date_entry}

For more than 2 columns you can do something like:

validates :empcode, :uniqueness => {:scope => [:date_entry, :description]}

Upvotes: 13

Mike Lewis
Mike Lewis

Reputation: 64177

validates_uniqueness_of :employee_code, :scope => [:date_entry]

Three and more columns, all you need to do is add elements to the scope list:

validates_uniqueness_of :employee_code, :scope => [:date_entry, :another_column]

or Rails 3:

validates :employee_code, :uniqueness => {:scope => :date_entry}

Upvotes: 35

Related Questions