73

I need to validate the uniqueness of two fields in an object (row) before I add them. Employee_id and area_id are the two fields in my emp_area table. There can be multiple records with the same employee_id and multiple records with the same area_id, but no two records can have the same employee_id and the same area_id. This is sort of like two fields making up a primary-key or unique-key.

How can I do this.

Thanks

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
johnc
  • 741
  • 1
  • 5
  • 4
  • possible duplicate of [How do you validate uniqueness of a pair of ids in Ruby on Rails?](http://stackoverflow.com/questions/923796/how-do-you-validate-uniqueness-of-a-pair-of-ids-in-ruby-on-rails) – Ciro Santilli OurBigBook.com Jul 01 '14 at 16:00

2 Answers2

99

what about this solution Validate combined values

validates :employee_id, uniqueness: { scope: :area_id }
Community
  • 1
  • 1
Naveed
  • 11,057
  • 2
  • 44
  • 63
  • 3
    This seems to be preferred over `validates_uniqueness_of` as it allows you set multiple validations on the same form, e.g. `presence: true`. – Joshua Pinter Apr 27 '15 at 19:26
  • For correct highlight of the error messages I created also validates :area_id, uniqueness: { scope: employee_id } – Mauro Aug 05 '16 at 14:28
69
validates_uniqueness_of :employee_id, :scope => :area_id
JRL
  • 76,767
  • 18
  • 98
  • 146