Cannot eagerly load the polymorphic association
Asked Answered
Z

3

8

I get the error Cannot eagerly load the polymorphic association :messageable_fromuser

online = Message.all.joins(:messageable_fromuser)

I tried

online = Message.all.includes(:messageable_fromuser)

But it doesn't include the joined table in the result. I see two queries in my log when using includes. I don't know why people recommend using includes to eager load. How is two queries going to join anything?

Zerk answered 15/10, 2014 at 0:32 Comment(1)
At first it would be quite helpful, if you would post your model classes that are involved. Further on the second query you see in your logs should end with something like IN (1, 10) (the actual numbers will differ). This part of the query fills the role of joining both tables. W3schools has a simple example of the IN operator.Oberland
Y
7

With polymorphic you need to manually set the joins.

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

If you want to dynamically get the relationship you could do:

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)
Yeisk answered 29/8, 2019 at 11:49 Comment(2)
This JOIN statements won't work this way because they are not complete.Bouffe
Won't this only filter the associations? I am guessing we'll also need to preload the messageable_fromuser, if it's to be accessed somewhere that isRamble
D
7

Using preload should solve the error:

online = Message.preload(:messageable_fromuser)
Defiant answered 7/4, 2021 at 12:16 Comment(0)
T
0

A lot of time is passed but I also have faced this issue and for me using preloading is helped. https://github.com/rails/rails/blob/6-0-stable/activerecord/lib/active_record/associations.rb#L161

Tabby answered 29/8, 2019 at 11:32 Comment(1)
An example would have been nice how to use it in the case of the thread openers question.Bouffe

© 2022 - 2024 — McMap. All rights reserved.