Rails: unexpected behavior updating a shared instance
- by Pascal Lindelauf
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"?