Search code examples
ruby-on-railsrubyruby-on-rails-4activerecordruby-on-rails-5

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.

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)


Solution

  • 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