3

How do I add database constrain for following statement written in rails model

validates :column_1, uniqueness: { scope: [:column_2, :column_3] }

Thank in advance.

Shambhu
  • 71
  • 7
  • http://stackoverflow.com/a/29961501/4481312 – marmeladze Feb 06 '17 at 12:16
  • Possible duplicate of [Validate uniqueness of multiple columns](http://stackoverflow.com/questions/4870961/validate-uniqueness-of-multiple-columns) – Eyeslandic Feb 06 '17 at 13:14
  • 1
    Possible duplicate of [A migration to add unique constraint to a combination of columns](https://stackoverflow.com/questions/3370271/a-migration-to-add-unique-constraint-to-a-combination-of-columns) – Ja͢ck Jan 12 '18 at 01:42

1 Answers1

3

Run the following migration:

def change    
  add_index :table_name, [:column_1, :column_2,:column_3], unique: true
end
Othmane El Kesri
  • 603
  • 5
  • 16
  • Thank you @Othmane El Kesri ! adding above restrict to add same combinition for column_2 and column_3 but in my case, I want combinition with column_1 too. So adding `add_index :table_name, [column_1,:column_2,:column_3], unique: true`. Is that correct way? – Shambhu Feb 06 '17 at 13:04
  • i updated my answer, please check it if it's the correct one – Othmane El Kesri Feb 06 '17 at 16:20