【问题标题】:Cannot eagerly load the polymorphic association不能急切地加载多态关联
【发布时间】:2014-10-15 00:32:44
【问题描述】:

我得到了错误 无法急切加载多态关联:messageable_fromuser

online = Message.all.joins(:messageable_fromuser)

我试过了

online = Message.all.includes(:messageable_fromuser)

但它不包括结果中的联接表。使用包含时,我在日志中看到两个查询。我不知道为什么人们建议使用包含来急切加载。两个查询如何连接任何东西?

【问题讨论】:

  • 首先,如果您发布所涉及的模型类,这将非常有帮助。进一步在您在日志中看到的第二个查询应该以 IN (1, 10) 之类的结尾(实际数字会有所不同)。这部分查询填补了连接两个表的作用。 W3schools 有一个简单的 IN 运算符示例。

标签: ruby-on-rails join polymorphic-associations


【解决方案1】:

对于多态,您需要手动设置连接。

Message.joins("JOIN polymorphic_association.owner_id = messages.id AND polymorphic_association.owner_type = 'User'")

如果你想动态获取你可以做的关系:

owner_type = 'User' # or whatever other models can have the association
Message.joins("JOIN polymorphic_association.owner_id = messages.id AND polymorphic_association.owner_type = ?", owner_type)

【讨论】:

  • 此 JOIN 语句不会以这种方式工作,因为它们不完整。
  • 这不会只过滤关联吗?我猜我们还需要预加载 messageable_fromuser,如果要在某个地方访问它
【解决方案2】:

使用preload 应该可以解决错误:

online = Message.preload(:messageable_fromuser)

【讨论】:

    【解决方案3】:

    很多时间过去了,但我也遇到了这个问题,对我来说使用preloading 很有帮助。 https://github.com/rails/rails/blob/6-0-stable/activerecord/lib/active_record/associations.rb#L161

    【讨论】:

    • 在线程开启者问题的情况下如何使用它的示例会很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 2017-12-26
    • 2010-12-01
    • 2017-08-28
    • 2013-10-17
    • 1970-01-01
    相关资源
    最近更新 更多