繁体   English   中英

rails迁移中的唯一外键

[英]Unique foreign key in rails migration

在迁移文件中,我使用以下语法添加外键。

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      |         |               |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

使用迁移添加唯一外键的正确方法是什么?

我可以在模型本身中添加唯一性验证。 但如果我有多个工人在运行,它就不会万无一失。 参考

在 Rails 5 中,您可以使用更优雅的方式完成相同的操作:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM