How would you choose between Belongs_to And Has_one ?
How would you choose between Belongs_to And Has_one ?
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
belongs_to: The foreign key is in the table of the model declaring the belongs_to association.Can you explain the difference between ActiveSupport’s HashWithIndifferentAccess and Ruby’s Hash ?
Xem chi tiếtDoes Ruby Support Single Inheritance/Multiple Inheritance Or Both?
Xem chi tiếtExplain how you define Instance Variable, Global Variable and Class Variable in Ruby?
Xem chi tiếtĐăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.