在迁移文件中,我使用以下语法添加外键。
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 | | |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
使用迁移添加唯一外键的正确方法是什么?
我本可以在模型本身中添加唯一性验证。但如果我有多个工作人员在运行,它就不会万无一失。 ( Reference )
最佳答案
在 Rails 5 中,您可以使用更优雅的方式完成相同的操作:
t.belongs_to :user, foreign_key: true, index: { unique: true }
这将生成一个外键约束以及一个唯一索引。如果这是必需的关联,请不要忘记添加 null: false
(在原始问题的情况下听起来很像)。
请注意,belongs_to
只是references
的别名。
关于ruby-on-rails - rails迁移中的唯一外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32681764/