Reputation: 1921
I need to remove related entity from collection. So for example I have M:N relation: project which has multiple users (and users can have multiple projects).
How can I remove user from project, but do not delete him?
# this removes user from project, but also deletes user
project.users.find(id: user._id).remove
Thanks
Upvotes: 0
Views: 39
Reputation: 392
Let's say we have band and it has multiple tags:
band = Band.all[1]
=> #<Band _id: 599d2c8a9d1fa2c5498024cc, name: "test_band", tag_ids: [BSON::ObjectId('599d2c8a9d1fa2c5498024cd'), BSON::ObjectId('599d2c8a9d1fa2c5498024ce'), BSON::ObjectId('599d2c8a9d1fa2c5498024cf')]>
Then if we try to delete one of related tag objects:
band.tags.delete(Tag.find(id: '599d2c8a9d1fa2c5498024cd')
...
MONGODB | localhost:27017 | test_development.update | SUCCEEDED | 0.000634s
=> #<Tag _id: 599d2c8a9d1fa2c5498024cd, name: "test_tag1", band_ids: []>
It will be removed from band.tags
array:
irb(main):088:0> band
=> #<Band _id: 599d2c8a9d1fa2c5498024cc, name: "test", tag_ids: [BSON::ObjectId('599d2c8a9d1fa2c5498024ce'), BSON::ObjectId('599d2c8a9d1fa2c5498024cf')]>
But that Tag still present as object:
Tag.find(id: '599d2c8a9d1fa2c5498024cd')
=> #<Tag _id: 599d2c8a9d1fa2c5498024cd, name: "test_tag1", band_ids: []>
Upvotes: 1