Reputation: 20014
A post has many comments. In my code I am trying to change an attribute of the first comment like so:
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"
Is this an expected AR behavior? If yes, how can I change attributes of associated records?
Upvotes: 0
Views: 26
Reputation: 160
First, assign the comment object to a variable, then make the change to that variable and save
post = Post.find(id)
comment = post.comments.first
comment.title = "foobar"
comment.title_changed? # true
comment.save
Upvotes: 0
Reputation: 4640
Yes, it is expected.
post.comments.first.title = "foobar"
just assigns the title but not saves it.
Right way to update is post.comments.first.update(title: "foobar")
.
Or you need to post.comments.first.save
after assigning a new title
Upvotes: 1