In Rails, how can I retrieve the object on a belongs_to association, without going through the database?
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.
You could use :inverse_of to set it. Read more about it here.
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:
p = Parent.find 41
# do this...
p.some_attr = 'some_value'
p.save
# OR this...
p.update_attribute(:some_attr, 'some_value')
c = p.children.build
c.parent
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.
精彩评论