如何从Mongoid模型中删除属性,即不仅仅是使它们的值无效

问题描述 投票:6回答:4

我正在试验Mongoid中的多态关联

class Group
    include Mongoid::Document
    belongs_to :groupable, polymorphic: true
end

class Album
    include Mongoid::Document
    has_many :groups, as: groupable
end

然后我决定反对它。所以我删除了上面所有的belongs_to和has_many行。然而在控制台中,每当我获得我试验过的Group记录时,它仍然具有这个“groupable_type”属性。我知道remove_attribute会使属性无效,但不会将其删除(听起来有点像JavaScript)。我如何从Mongoid中实际从数据库中删除此属性?

ruby-on-rails mongoid
4个回答
13
投票

你可以这样做:

Group.collection.update({},
                        {'$unset' => {:groupable_type => 1}},
                        :multi => true)

3
投票

从Mongoid的5.0.0版本开始,gem已经从使用Moped切换到使用具有不同更新语法的“官方ruby MongoDB驱动程序”。参考:https://docs.mongodb.org/ecosystem/drivers/ruby/

收集方法的文档在这里:http://api.mongodb.org/ruby/current/Mongo/Collection.html

有两种方法,“更新”和“update_many”。您可以使用update_many而不是指定“multi”选项来更新所有文档。

用于OP案例的示例:

Group.collection.update_many({}, {'$unset' => {'groupable_type' => true}})

请注意,您可以使用点表示法取消嵌入文档:

Group.collection.update_many({}, {'$unset' => {'embedded_doc.groupable_type' => true}})

请注意,MongoDB不支持取消/更新数组中的字段。有关信息和解决方法,请参阅此主题:https://jira.mongodb.org/browse/SERVER-1243


0
投票

我注意到在Moped 2.0.0.rc1中,更新方法已经收集了,但是这有效;

Group.collection.find().update(
                    {'$unset' => {:groupable_type => 1}},
                    :multi => true)     

0
投票

对于单个实例,有可能(至少在Mongoid的最新版本中)直接在您的实例上使用unset

Group.first.unset('groupable_type')
© www.soinside.com 2019 - 2024. All rights reserved.