在迁移文件中,我使用以下语法添加外键。
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 | | |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
如何使用迁移添加唯一的外键?
我本可以在模型本身中添加唯一性验证。但如果我有多个工作人员运行,这并不是万无一失的。(参考资料)