无法急切加载多态关联

Nat*_*at8 8 join ruby-on-rails polymorphic-associations

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

online = Message.all.joins(:messageable_fromuser)
Run Code Online (Sandbox Code Playgroud)

我试过

online = Message.all.includes(:messageable_fromuser)
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*eft 7

使用多态时,您需要手动设置连接。

Message.joins("JOIN polymorphic_association.owner_id = messages.id AND polymorphic_association.owner_type = 'User'")
Run Code Online (Sandbox Code Playgroud)

如果你想动态获取关系,你可以这样做:

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)
Run Code Online (Sandbox Code Playgroud)


Ale*_*der 7

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

online = Message.preload(:messageable_fromuser)
Run Code Online (Sandbox Code Playgroud)


kun*_*hir 0

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

  • 一个很好的例子是如何在线程开启问题的情况下使用它。 (9认同)