compsy
compsy

Reputation: 233

Rails Active Records : foreign_key vs references

This is my code

class CreatePosts < ActiveRecord::Migration[5.1]
  def change
    create_table :posts, id: :uuid do |t|
      t.string :name

      t.references :user, type: :uuid
      t.references :user, type: :uuid, foreign_key: true    

      t.timestamps
    end
  end
end

I am confused what is the difference b/w these line.Both lines of code are working fine to accomplish reference between table .

t.references :user, type: :uuid
t.references :user, type: :uuid, foreign_key: true   #what this line is doing 

Can anybody explain me when to use foreign_key or not .

I find the similar things while searching these

t.references :makers, foreign_key: { to_table: :office }

In above code foreign_key is not true. It referencing to some table. why is it so.

Upvotes: 4

Views: 5458

Answers (2)

Thanh
Thanh

Reputation: 8604

You can check the document of references here, it uses same options with add_reference.

So, the different is:

t.references :user, type: :uuid - Add a column without adding constraint.

t.references :user, type: :uuid, foreign_key: true - Add a column and foreign key constraint. If you don't specify foreign_key, it will be false.

foreign_key: { to_table: :table_name } - It's option to add a column with a custom name instead of convention name.

For example, in document:

add_reference(:products, :supplier, foreign_key: {to_table: :firms})

so, it will add a column name supplier_id to table products and add a foreign key to reference to firms table.

If you follow convention name, then you will want to add a column named firm_id instead of supplier_id.

Upvotes: 4

Abdullah Fadhel
Abdullah Fadhel

Reputation: 310

foreign_key: true will create a foreign key constraint, and without it ONLY the foreign key will be created.

to understand the difference between foreign key and foreign key constraint please visit this link.

specifying foreign_key: { to_table: :office } will make the foreign key reference the office table.

Upvotes: 3

Related Questions