Rails: unexpected behavior updating a shared instance
Posted
by Pascal Lindelauf
on Stack Overflow
See other posts from Stack Overflow
or by Pascal Lindelauf
Published on 2010-05-20T09:45:09Z
Indexed on
2010/05/20
9:50 UTC
Read the original article
Hit count: 246
ruby-on-rails
I have a User object, that is related to a Post object via two different association paths:
- Post --(has_many)--> comments --(belongs to)--> writer (of type User)
- Post --(belongs to)--> writer (of type User)
Say the following hold:
user1.name == "Bill"
post1.comments[1].writer == user1
post1.writer == user1
Now when I retrieve the post1 and its comments from the database and I update post1.comments[1].writer like so:
post1.comments[1].writer.name = "John"
I would expect post1.writer to equal "John" too. But it doesn't! It still equals "Bill".
So there seems to be some caching going on, but the kind I would not expect. I would expect Rails to be clever enough to load exactly one instance of the user with name "Bill"; instead is appears to load two individual ones: one for each association path.
Can someone explain how this works exactly and how I am to handle these types of situations the "Rails way"?
© Stack Overflow or respective owner