Reputation: 3105
Currently I have an address
column that is an embedded document in my users
table. The address
column contains the _id
for related rows in the address
table. Each user
can have many addresses
so there can be multiple embedded documents in the user
address
column if that user had more than one address.
How do I delete all address
embedded documents for a specific address id
? In my case, when a user deletes an address, I want to delete that specific address from ALL of the address
embedded documents in the users table.
Is this possible in the rails console?
Thanks
Upvotes: 1
Views: 347
Reputation: 10907
You can also do:
while User.where('addresses._id' => address.id).count > 0
User.collection.update({'addresses._id' => address.id},
{'$pull' => { :addresses => { '_id' => address.id } } },
:multi => true)
end
This will not run any callbacks. If you need any callbacks, you should use shingara's method but replace delete
with destroy
Upvotes: 0
Reputation: 46914
You can do :
User.where('addresses.id' => address.id).each do |u|
u.addresses.where(:id => address.id).delete
u.save
end
Upvotes: 1