【问题标题】:Rails 5 field _type not generated in mongoidRails 5 字段 _type 未在 mongoid 中生成
【发布时间】:2017-11-07 06:52:21
【问题描述】:

我有一个文档的类和子类,如下所示:

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

【问题讨论】:

  • 我猜首先不使用Core::Moderator 会导致Rails 不知道Core::User 有子类,因此不会加载STI 辅助方法。如果您先加载子类Core::Moderator 而不构建实例,然后再构建Core::User,会发生什么情况。
  • @spickermann 首先加载子类Core::Moderator,然后构建Core::User,创建字段_type。仅供参考,我有另一个应用程序,但使用具有相同模型结构的 rails 4.x.x,我不应该先加载子类,字段 _type 在构建类时生成。
  • 如果 Rails 的自动加载和预加载实现的内部结构在 4.x 和 5.1 之间发生了变化,我会感到非常惊讶,但如果 R​​ails 知道一个类有子类而没有加载至少一个,我会感到惊讶他们。
  • @spickermann 我找到了。如果我将true 设置为eager_load,则rails 知道一个类有子类。 stackoverflow.com/q/19839847/1297435
  • @max OP 在 Rails 应用程序中使用 Mongoid。这一点以及启用 Rails 的eager_load 解决了这个问题的事实让我确信这是一个 Rails 自动加载问题,而不是 Mongoid 引起的问题。

标签: ruby-on-rails ruby mongoid


【解决方案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 

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多