Robert Robert - 1 year ago 115
Ruby Question

Rails create join table how to validate uniqueness of pair

I've created a join table with

rails generate migration CreateJoinTableFoosBars foos bars

and it has indeed created a working joining table, however I can't see the model for it and thus I can't add the

validates_uniqueness_of :foo_id, scope: :bar_id

How can I do it in this case? Thanks in advance.

Answer Source

Add a unique index that includes both columns. That will prevent you from inserting a record that contains a duplicate foo_id/bar_id pair.

add_index :foo_bars, [ :foo_id, :bar_id ], unique: true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download