Rails 5 字段 _type 未在 mongoid 中生成

Rails 5 field _type not generated in mongoid

我有 class & subclass 和一个文件看起来像 :

class Core::User
  include Mongoid::Document
  include Mongoid::Timestamps

  store_in collection: 'users'
end

class Core::Moderator < Core::User

end

我尝试从控制台添加用户

2.4.2 :002 >  user = Core::User.new(email: 'email@domain.com', name: 'new user')
 => #<Core::User _id: BSON::ObjectId('5a015465fe37a86430b1e0ff'), created_at: nil, email: "email@domain.com", name: "new_user", updated_at: nil> 
2.4.2 :003 > user.save
 => true 
2.4.2 :004 > user._type
NoMethodError: undefined method `_type' for #<Core::User:0x0000000003e77ea0>
    from (irb):4

然后添加新版主:

2.4.2 :005 > moderator = Core::Moderator.new(email: 'email2@domail.com', name: 'new moderator')
#<Core::Moderator _id: BSON::ObjectId('5a015600fe37a86430b1e100'), created_at: nil, email: "email2@domain.com", name: "new moderator", updated_at: nil>
2.4.2 :006 > moderator.save
=> true 
2.4.2 :007 > moderator._type
=> "Core::Moderator"

接下来再次添加新用户:

2.4.2 :008 >  user = Core::User.new(email: 'email3@domain.com', name: 'new user 2')
 => #<Core::User _id: BSON::ObjectId('5a015704fe37a86430b1e101'), created_at: nil, email: "email3@domain.com", name: "new user 2", updated_at: nil> 
2.4.2 :009 > user.save
 => true 
2.4.2 :010 > user._type
 => "Core::User"

为什么我应该先创建子 class 以获得父 class 上的字段 _type?每次我启动新控制台并创建新用户 (Core::User) 时,字段 _type 未生成。

我用户 Ruby 2.4.2,Rails 5.1.4,Mongoid 6.2.1

为了使继承在 Mongoid 中按预期工作,您需要设置 preload_models: true。否则模型无法知道它有子类。

# config/mongoid.yml
development:
  # ...
  options: 
    # ...
    # Preload all models in development, needed when models use
    # inheritance. (default: false)
    preload_models: true