Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a document's _type in Mongoid?

I have the following models inside a Rails application:

class User
  include Mongoid::Document
  ...
end

class Admin < User
  ...
end

I get a user:

u = User.find(some_key)

And try to change the _type:

u._type  # => "User"
u._type = "Admin"
u.save
u._type  # => "Admin"

But if I reload the object it's still a user:

u.reload
u._type = "User"

What is the correct way to change this?

like image 257
Federico Builes Avatar asked Mar 15 '11 01:03

Federico Builes


2 Answers

you could also use Model#update_attribute to stay with mongoid:

user.update_attribute(:_type, "Admin")
like image 137
tmaier Avatar answered Oct 22 '22 09:10

tmaier


Ended up solving it by using a raw MongoDB query:

users.update( { :"_id" => user.id }, { :"$set" => { :"_type" => "Admin" }})
like image 38
Federico Builes Avatar answered Oct 22 '22 10:10

Federico Builes