我得到以下错误:无法立即加载多态关联:messageable_fromuser
online = Message.all.joins(:messageable_fromuser)我试过了
online = Message.all.includes(:messageable_fromuser)但它不会在结果中包含连接的表。使用includes时,我在日志中看到两个查询。我不知道为什么人们推荐使用includes来快速加载。两个查询如何连接任何内容?
发布于 2019-08-29 19:49:33
使用多态时,您需要手动设置连接。
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)发布于 2021-04-07 20:16:08
使用preload应该可以解决这个错误:
online = Message.preload(:messageable_fromuser)发布于 2019-08-29 19:32:20
很多时间过去了,但我也遇到过这个问题,对我来说,使用preloading是有帮助的。https://github.com/rails/rails/blob/6-0-stable/activerecord/lib/active_record/associations.rb#L161
https://stackoverflow.com/questions/26372613
复制相似问题