Nik*_*til 12 ruby mysql activerecord ruby-on-rails ruby-on-rails-4
在迁移文件中,我使用以下语法添加外键.
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
Run Code Online (Sandbox Code Playgroud)
但是: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 | | |
+-------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
Run Code Online (Sandbox Code Playgroud)
使用迁移添加唯一外键的正确方法是什么?
我可以在模型中添加唯一性验证.但如果我有多个工人在跑,那就不会万无一失.(参考)
Kos*_*sis 27
在Rails 5中,你可以用更优雅的方式完成同样的工作:
t.belongs_to :user, foreign_key: true, index: { unique: true }
Run Code Online (Sandbox Code Playgroud)
这将生成外键约束以及唯一索引.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3927 次 |
| 最近记录: |