如何防止从数据库重新加载双向关联

时间:2014-07-16 17:46:37

标签: ruby-on-rails ruby-on-rails-4

我们说我有两种模式:

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">

这会导致从DB重新加载联系人记录。 我希望它能够返回更新的“肮脏的”#39;已经在记忆中的模型:

#=> <Contact id: 1, name: "Michael Jackson">
  1. 为什么在更新的Contact对象已经加载到内存中时,它正在向数据库进行往返?

  2. 如何让它返回“肮脏的”&#39;在记忆对象?

1 个答案:

答案 0 :(得分:0)

您需要双向关联。为此,请查看rails guide。你只需要添加:

has_many :emails, inverse_of: :contacts
belongs_to :contact, inverse_of: :email