Mongoid - 从M:N集合中删除实体但不删除它

时间:2017-08-21 18:26:04

标签: ruby many-to-many mongoid

我需要从集合中删除相关实体。 例如,我有M:N关系:项目有多个用户(用户可以有多个项目)。

如何从项目中删除用户,但不删除他?

# this removes user from project, but also deletes user
project.users.find(id: user._id).remove

由于

1 个答案:

答案 0 :(得分:1)

我们说我们有乐队,它有多个标签:

band = Band.all[1]
=> #<Band _id: 599d2c8a9d1fa2c5498024cc, name: "test_band", tag_ids: [BSON::ObjectId('599d2c8a9d1fa2c5498024cd'), BSON::ObjectId('599d2c8a9d1fa2c5498024ce'), BSON::ObjectId('599d2c8a9d1fa2c5498024cf')]>

然后,如果我们尝试删除一个相关的标记对象:

band.tags.delete(Tag.find(id: '599d2c8a9d1fa2c5498024cd')
...
MONGODB | localhost:27017 | test_development.update | SUCCEEDED | 0.000634s
=> #<Tag _id: 599d2c8a9d1fa2c5498024cd, name: "test_tag1", band_ids: []>

它将从band.tags数组中删除:

irb(main):088:0> band
=> #<Band _id: 599d2c8a9d1fa2c5498024cc, name: "test", tag_ids: [BSON::ObjectId('599d2c8a9d1fa2c5498024ce'), BSON::ObjectId('599d2c8a9d1fa2c5498024cf')]>

但该标签仍然作为对象存在:

Tag.find(id: '599d2c8a9d1fa2c5498024cd')
=> #<Tag _id: 599d2c8a9d1fa2c5498024cd, name: "test_tag1", band_ids: []>