Reputation: 1067
I have an Item class and a Comment class. Items have many embedded comments.
Comments also store a user's username, so if a user changes their username, I want to update all of their comments.
I want to do something like this (obviously it doesn't work):
Item.where('comments.username' => 'elvis33').update_all('comments.username' => 'elvis')
How do I do this?
Upvotes: 1
Views: 819
Reputation: 65877
$ positional operator has the limitation only applies to the first matched item in the query
. There is a open issue in Jira regarding the issue (Vote it if you really need the feature)
So that leaves us no choice other than retrieving the comments collection and update all comments by looping it.
items = Item.only(:comments).where('comments.username' => 'elvis33')
items.each do |item|
item.comments.select {|com| com.username == 'elvis33'}.each do |comment|
comment.username = 'elvis'
end
item.save
end
The above code updates each item once with all modified comment user names. I haven't tested the code.
Upvotes: 2
Reputation: 678
Since username is actually part of an document of an embedded array, you have to use the positional operator like this:
Item.where('comments.username' => 'elvis33').update_all('comments.$.username' => 'elvis')
Upvotes: 0