Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 778
johan Avatar asked Mar 31 '11 02:03

johan


1 Answers

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}
like image 133
Mike Lewis Avatar answered Oct 21 '22 21:10

Mike Lewis