Nik So
Nik So

Reputation: 16811

how to remove attributes from a Mongoid Model, i.e., not just nullifying their values

I was experimenting the polymorphic associaton in Mongoid

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

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

then I decided against it. So I removed all those belongs_to and has_many lines above. Yet in the console, whenever I get a Group record that I experimented with, it still has this "groupable_type" attribute. I know remove_attribute nullify the attribute, but does not remove it( sounds a bit like JavaScript). How can I actually remove this attribute from the database from Mongoid?

Upvotes: 8

Views: 4386

Answers (4)

Cyril Duchon-Doris
Cyril Duchon-Doris

Reputation: 13949

For a single instance, it is possible (at least in recent versions of Mongoid) to use directly unset on your instance

Group.first.unset('groupable_type')

Upvotes: 1

adailey
adailey

Reputation: 163

As of version 5.0.0 of Mongoid, the gem has switched from using Moped to use the 'official ruby MongoDB driver' which has a different syntax for updates. Reference: https://docs.mongodb.org/ecosystem/drivers/ruby/

The documentation for collection methods is here: http://api.mongodb.org/ruby/current/Mongo/Collection.html

There are 2 methods, "update" and "update_many". You can use update_many instead of specifying the 'multi' option to update all documents.

Example use for the OPs case:

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

Note you can unset embedded documents using dot notation:

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

Note it is not well supported by MongoDB to unset / update fields within an array. See this thread for info and workarounds: https://jira.mongodb.org/browse/SERVER-1243.

Upvotes: 5

SteveO7
SteveO7

Reputation: 2460

I noticed in Moped 2.0.0.rc1 the update method is gone on collection, but this works;

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

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

You could do this:

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

Upvotes: 13

Related Questions