Rails迁移中的唯一外键

20
在迁移文件中,我使用以下语法添加外键。
class CreatePreferences < ActiveRecord::Migration
  def change
    create_table :preferences do |t|
      t.integer :user_id, null: false
      t.timestamps null: false
    end
    add_foreign_key :preferences, :users, column: :user_id, dependent: :destroy, :unique => true
  end
end

但是:unique => true没有起作用。

mysql> show indexes from preferences;
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table       | Non_unique | Key_name            | Seq_in_index | Column_name  | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| preferences |          0 | PRIMARY             |            1 | id           | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
| preferences |          1 | fk_rails_87f1c9c7bd |            1 | user_id      | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

如何使用迁移添加唯一的外键?

我本可以在模型本身中添加唯一性验证。但如果我有多个工作人员运行,这并不是万无一失的。(参考资料


1
我想你应该在数据库层面上添加索引,使其唯一。 - Pavan
2个回答

47

在Rails 5中,您可以使用更优雅的方式实现相同功能:

t.belongs_to :user, foreign_key: true, index: { unique: true }

这将生成一个外键约束以及一个唯一索引。如果这是必需的关联(在原始问题的情况下听起来像是),不要忘记添加 null: false

请注意,belongs_to 只是 references 的别名。


9
class CreatePreferences < ActiveRecord::Migration
  def change
    create_table :preferences do |t|
      t.integer :user_id, null: false
      t.timestamps null: false
    end
    add_foreign_key :preferences, :users, column: :user_id, dependent: :destroy, :unique => true
    add_index :preferences, :user_id, unique: true
  end
end

我需要在 add_foreign_keyadd_index 中都使用 unique 吗? - Nikhil Patil
“foreign_key”和“index”是不同的东西,所以我认为你可以同时拥有“unique”。 - Andrey Deineko
1
截至Rails 5.2,unique不是add_foreign_key()的有效选项,并且会被静默地忽略。但它对于add_index()是一个有效选项。 - TanguyP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接