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.
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:
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).
Note that belongs_to
is just an alias for references
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With