在Rails中,如何在不通过数据库的情况下检索belongs_to关联上的对象?
考虑以下设置:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
以及此控制台会话:
>> p = Parent.find 41
>> p.some_attr = 'some_value'
>> c = p.children.build
>> c.parent
通过观察我的日志文件,我可以看到 c.parent 正在数据库中查询父对象。我想访问现有的内存中对象 (p),因为我需要访问父级的 some_attr 值,该值尚未存储在数据库中。有什么办法可以做到这一点吗? c.parent(force_reload=false) 无法让我到达那里。
Consider the following setup:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
And this console session:
>> p = Parent.find 41
>> p.some_attr = 'some_value'
>> c = p.children.build
>> c.parent
By watching my log files, I can see that c.parent is querying the db for the parent object. I want instead to access the existing in-memory object (p), because I need access to the parent's some_attr value, which is not yet stored in the database. Is there any way of doing this? c.parent(force_reload=false) doesn't get me there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 :inverse_of 来设置它。在此处了解更多相关信息。
You could use :inverse_of to set it. Read more about it here.
ActiveRecord 并不努力保证相同数据库对象的内存中对象都是相同的。这是DataMapper 所保证的。
我意识到你的例子可能是为了提出你的问题而简化的,但只是从天真的角度来看——你为什么不直接使用 p 而不是 c.parent ?
另一个可能有用的建议,将更新保存到数据库的父级:
我不确定 c.parent(false) (“不要从数据库重新加载”)在这里是否可以解决问题,因为它是一个新的 Child 对象。但你也可以尝试一下。
ActiveRecord doesn't endeavor to guarantee that in-memory objects for the same database objects are all the same. This is something that DataMapper does guarantee.
I realize your example is probably simplified in order to ask your question, but just from a naive look at it -- why don't you just use p instead of c.parent?
Another possibly helpful suggestion, save the update to parent to the db:
I'm not sure if
c.parent(false)
("don't reload from the db") will do the trick here, since it's a fresh Child object. But you can try that too.