How would you choose betwe...
How would you choose betwe...
Choosing between belongs_to
and has_one
in Ruby on Rails depends on the direction of the relationship and where the foreign key is stored. Here’s a detailed explanation to help you understand and decide which one to use:
belongs_to
Association:
belongs_to
association is used when the model declaring it contains the foreign key.Account
belongs to a Supplier
, the accounts
table will have a supplier_id
column.class Account < ApplicationRecord
belongs_to :supplier
end
has_one
Association:
has_one
association is used when the other model contains the foreign key.Supplier
has one Account
, the accounts
table will have a supplier_id
column.class Supplier < ApplicationRecord
has_one :account
end
Foreign Key Placement:
belongs_to
: The foreign key is in the table of the model declaring the belongs_to
association.has_one
: The foreign key is in the table of the other model.Semantic Meaning:
belongs_to
: Indicates ownership or a direct reference to another model.has_one
: Indicates that another model references this model.Consider a scenario with Supplier
and Account
models:
Supplier
has one Account
.Account
belongs to a Supplier
.The corresponding migrations might look like this:
class CreateSuppliers < ActiveRecord::Migration[7.1]
def change
create_table :suppliers do |t|
t.string :name
t.timestamps
end
create_table :accounts do |t|...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào