1

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

Goalie
  • 3,045
  • 5
  • 35
  • 46

2 Answers2

1

You can do :

User.where('addresses.id' => address.id).each do |u|
  u.addresses.where(:id => address.id).delete
  u.save
end
shingara
  • 46,608
  • 11
  • 99
  • 105
0

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

rubish
  • 10,887
  • 3
  • 43
  • 57
  • This is not doing anything. I even tried `User.where('addresses._id' => address.id)` and it returns nil. Its like its not seeing the embedded documents. – Goalie Apr 03 '12 at 02:19
  • @Goalie In case you are not setting custom id for addresses and letting mongo set the ID, then none of the documents will have the same ID(even embedded ones). There must be some other way for you to identify if two addresses are same or not. You should use that instead of `'addresses._id' => address.id` – rubish Apr 03 '12 at 07:22