简体   繁体   English

rails迁移中的唯一外键

[英]Unique foreign key in rails migration

In migrations file, I'm adding foreign key using below syntax.在迁移文件中,我使用以下语法添加外键。

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

But :unique => true is not working.但是: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      |         |               |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

What is the right way to add a unique foreign key using migrations?使用迁移添加唯一外键的正确方法是什么?

I could've added uniqueness validations in the model itself.我可以在模型本身中添加唯一性验证。 But it won't be foolproof if I have multiple workers running.但如果我有多个工人在运行,它就不会万无一失。 ( Reference ) 参考

In Rails 5 you can accomplish the same with the more elegant:在 Rails 5 中,您可以使用更优雅的方式完成相同的操作:

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

This will generate a foreign key constraint as well as a unique index.这将生成一个外键约束以及一个唯一索引。 Don't forget to add null: false if this is a required association (sounds like it in the case of the original question).如果这是必需的关联,请不要忘记添加null: false (在原始问题的情况下听起来很像)。

Note that belongs_to is just an alias for references .请注意, 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