views:

46

answers:

1

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"? [edit] Am I really supposed to litter my code with reload statements, like Slobodan's solution suggests?

A: 

Rails won't "load exactly one instance of the user". Comment writer and Post writer are separate. You would have to save the changes and reload Post.

Slobodan Kovacevic
Ok. That's a pain in my case, since I'm updating that name conditionally as a result of an event (e.g. a before_destroy on a comment). Since this is rather decoupled from the code using the post1.writer, how am I to do this elegantly (=not resort to litter my code with reload statements, just in case...)?
Pascal Lindelauf
If you are destroying a comment simply perform destroy and then redirect to some other page which will actually reload the record.
Slobodan Kovacevic