【问题标题】:Mongoid: eager loading relations in parent and its subclassesMongoid:在父类及其子类中急切加载关系
【发布时间】:2014-01-03 13:56:40
【问题描述】:

我在 mongoid 中使用子类,我希望加载父类及其子类的关系。

class Event
   include Mongoid::Document
   belongs_to :modifier
end

class Fixture < Event
   belongs_to :club
end

当我运行Event.includes(:modifier, :club) 时,我得到:

Mongoid::Errors::InvalidIncludes:
Problem:
Invalid includes directive: Event.includes(:modifier, :club)
Summary:
Eager loading in Mongoid only supports providing arguments to 
Event.includes that are the names of relations on the Event model, 
and only supports one     level of eager loading. (ie, eager
loading associations not on the Event but one step away via 
another relation is not allowed.
Resolution:
Ensure that each parameter passed to Event.includes is a valid name
of a relation on the Event model. These are: "modifier".

错误消息是合理的,但我想知道是否有解决方法,没有对每个类运行单独的查询?

我还希望能够链接更多标准,即Event.includes(:modifier, :club).desc(:updated_at),而不是在 rails 中对结果数组进行排序。

版本:Mongoid v3.16 和 Rails 3.2.15


编辑:我最好说清楚我想要什么。

我想要所有事件和所有固定装置文档。 我还想要它们的所有关系:Events 和 Fixtures 上的修饰符,以及 Fixtures 上的俱乐部。 而且我希望一次从 mongo 中检索这些相关文档,即通常使用 '.includes()' 方法通过'eager loading' 完成。 还会有更多的子类,即class Election &lt; Eventsclass Seminar &lt; Events。所以我想避免单独查询每个子类。 我还想链接更多标准,例如desc(:updated_at)

【问题讨论】:

  • 事件和玩家是什么关系?
  • 谢谢@kdeisz,:player 应该是 :club - 更新了。
  • Event和Fixture有什么关系?
  • 他们不是关系; Fixture 是 Event 的子类,它们的文档存储在同一个集合“events”中。我更新了示例,以明确 Event 是 MongoId 模型。

标签: ruby-on-rails mongoid eager-loading


【解决方案1】:

我不太确定你想做什么,但我想这可以解决你的问题。

Event.where(:modifier_id.ne => nil, :club_id.ne => nil).desc(:updated_at)

让我知道这是否适合您。

【讨论】:

  • 您的代码将返回所有夹具但不返回事件,并且不会急切加载关系。但我想要所有事件及其修饰符,以及所有夹具及其各自的修饰符和俱乐部(请参阅mongoid.org/en/mongoid/docs/querying.html 中的“急切加载”)
  • 你试过“Fixture.includes(:modifier, :club)”吗? Fixture 扩展了 Event,因此修饰符是 Fixture 上的有效属性。
  • 我怀疑我没有足够清楚地解释问题 - 我会尽快更新问题。
【解决方案2】:

到目前为止,MongoID 不支持嵌套文档预加载。你最好看看这个gem

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 1970-01-01
    • 2021-04-28
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多