[英]How to prevent a two way association from being reloaded from the database
假設我有兩個模型:
class Contact < ActiveRecord::Base
has_many :emails
end
class Email < ActiveRecord::Base
belongs_to :contact
end
從數據庫中提取一條記錄:
contact = Contact.first
#=> <Contact id: 1, name: "John Doe">
# Change his name, but don't save it
contact.name = "Michael Jackson"
# Let's get his email address
email = contact.emails.first
#=> <Email id: 1, address: "johndoe@example.com">
# Now try to reference the contact of the email:
email.contact
#=> <Contact id: 1, name: "John Doe">
這將導致聯系記錄從數據庫中重新加載。 我希望它返回已在內存中的更新的“臟”模型:
#=> <Contact id: 1, name: "Michael Jackson">
當更新的Contact對象已加載到內存中時,為什么要往返數據庫?
我如何獲取它以返回內存對象中的“臟污”?
您需要雙向關聯。 看看為此的導軌指南 。 您只需要添加:
has_many :emails, inverse_of: :contacts
belongs_to :contact, inverse_of: :email
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.