I have an issue where I seem (unintentionally) to have more than 1
activerecord object/instance referring to the same database record.
How do I ensure that when I update the record, all instances are
refreshed with the same data ?
It sounds like “identity map” which is being added to activerecord for
rail 3.1 may solve this, but is there a solution for rails 3.0 ?
I have an issue where I seem (unintentionally) to have more than 1
activerecord object/instance referring to the same database record.
How do I ensure that when I update the record, all instances are
refreshed with the same data ?
I don’t think this can be done on a global level. You need to call
reload
on
each of the instances to be sure that you have a fresh copy out of the
db.
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.) :
Child.create(:parent => parent)
but not
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.
should create a record with the same attributes as the record created
in
2).
If this isn’t happening then you need to check your associations. Can
you
share some code
regarding the associations?
I’m sure you’re just giving an example above but parent.childs should be
parent.children.
Also, I did discover a way to find all objects related to a given
I just used childs to show it was the plural. Would rails pluralize
child to children ?
All the attributes match correct in both cases - including parent_id -
but not parent. I assume the parent object is not a real attribute, as
only parent_id is shown when I do an inspect.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.