Augusto Carmo
Augusto Carmo

Reputation: 4964

How to add a unique index between two references columns in Rails Migration

I have the following migration:

create_table :product_attr_vals do |t|
  t.references :product, foreign_key: true
  t.references :attr_val, foreign_key: true

  t.timestamps
end

How can I add a unique index for the both t.references?

Upvotes: 0

Views: 478

Answers (1)

fongfan999
fongfan999

Reputation: 2624

Try to the following:

create_table :product_attr_vals do |t|
  t.references :product, foreign_key: true
  t.references :attr_val, foreign_key: true

  t.timestamps
end

# Add this line
add_index :product_attr_vals, [:product_id, : attr_val_id], unique: true

Upvotes: 3

Related Questions