帖子有很多评论。在我的代码中,我试图像这样更改第一个注释的属性:
post = Post.find(id)
post.comments.first.title # "initial title"
post.comments.first.title = "foobar"
post.comments.first.title_changed? # false
post.comments.first.title # "initial title"
这是预期的AR行为吗?如果是,如何更改关联记录的属性?
答案 0 :(得分:1)
是的,这是预期的。
post.comments.first.title = "foobar"
仅分配标题,但不保存。
正确的更新方式是post.comments.first.update(title: "foobar")
。
或者您需要在分配新标题后post.comments.first.save
答案 1 :(得分:0)
首先,将注释对象分配给一个变量,然后对该变量进行更改并保存
post = Post.find(id)
comment = post.comments.first
comment.title = "foobar"
comment.title_changed? # true
comment.save