[Rails] Re: refreshing multiple activerecord objects referring to same database record
My problem occurs when trying to modify a parent record from a child,
using an after_create callback in the child is created (they have a
has_many / belongs_to association).
After some more testing (checking object ids), I can get a test to
pass if I use (e.g.) :
1) Child.create(:parent => parent)
but not
2) parent.childs.create
I suspect that in 1), the child gets the original parent object passed
in, but in the second, it only gets the id, and, if needed, rails
creates a temp parent object from the id, which means I'm updating the
temp parent object (and the database if it is saved!), not the
original parent object in the parent.childs.create call, as I'd
expected. For the second way to work, I need always add a
parent.reload after a parent.childs.create.
Is this how rails/activerecord always works ? Is it a bug ?
Also, I did discover a way to find all objects related to a given
record
ObjectSpace.each_object(parent) do |temp_parent| if temp_parent.id
== parent.id ...
, but it's too slow.
For now, I just have to remember to always use the
Child.create(:parent => parent) form, but unless, someone has another
suggestion, I'll likely migrate to rails 3.1 soon, to get identity
map. For me, this should give more intuitive behaviour for
activerecord.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home