Reputation: 2329
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
.
Case 1: If the employee_code
and date_entry
combination already exist it won't allow to save another record with the same employee_code
and date_entry
.
Case 2: If the employee_code
and date_entry
exists but not on the same record, it will allow to save the field.
Upvotes: 15
Views: 13024
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
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