如何在Mongoid中更改文档的_type?

我在Rails应用程序中有以下模型:

class User include Mongoid::Document ... end class Admin < User ... end 

我得到一个用户:

 u = User.find(some_key) 

并尝试更改_type:

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

但是,如果我重新加载对象,它仍然是一个用户:

 u.reload u._type = "User" 

改变这个的正确方法是什么?

你也可以使用Model#update_attribute来保持mongoid:

 user.update_attribute(:_type, "Admin") 

通过使用原始MongoDB查询结束解决它:

 users.update( { :"_id" => user.id }, { :"$set" => { :"_type" => "Admin" }})