开发者

Rails: Updating an object referenced via different association paths

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 = "Joh开发者_运维百科n"

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜