Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 884
compsy Avatar asked Oct 26 '25 05:10

compsy


1 Answers

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.

like image 166
Thanh Avatar answered Oct 28 '25 20:10

Thanh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!