如何在Rails迁移中的两个引用列之间添加唯一索引

时间:2018-03-11 14:13:48

标签: ruby-on-rails database-migration

我有以下迁移:

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

  t.timestamps
end

如何为t.references

添加唯一索引

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

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