Reputation: 151
I'm confused about belongs_to and foreign key in rails. When we use belongs_to in rails migrations, it seems like it creates a foreign key on the child table that we can access from the parent table. However, in the rails documentation, there is a situation that uses both in one column.
create_table :accounts do |t|
t.belongs_to :supplier, index: { unique: true }, foreign_key: true
# ...
end
Can somebody explain this situation and explain the what belongs_to and foreign_key: true exactly does?
Upvotes: 0
Views: 32
Reputation: 30453
t.belongs_to :supplier
adds supplier_id
to accounts
.
index: { unique: true }
creates a database index for the column.
foreign_key: true
creates a foreign key constraint for the column.
I recommend you to read Active Record Migrations — Ruby on Rails Guides.
Indexes speed up data retrieval operations.
Foreign keys help to maintain referential integrity.
Upvotes: 1