Rails 5 field _type不是在mongoid中生成的

时间:2017-11-07 06:52:22

标签: ruby-on-rails ruby mongoid

我有班级&具有一个文档的子类如下:

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"

为什么我应首先创建子类以在父类上获取字段_type?每次我启动新的控制台并创建新用户(Core::User),而不是生成的字段_type

我用户Ruby 2.4.2,Rails 5.1.4,Mongoid 6.2.1

1 个答案:

答案 0 :(得分: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