Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: how do I do eager loading? #251

Closed
rstacruz opened this issue Feb 4, 2016 · 5 comments
Closed

Question: how do I do eager loading? #251

rstacruz opened this issue Feb 4, 2016 · 5 comments

Comments

@rstacruz
Copy link

rstacruz commented Feb 4, 2016

I'd like to be able to do this:

PublicActivity::Activity.all.includes(trackable: [:photos, :author])

But this isn't exactly possible like so, because trackable is polymorphic. I'll get errors like so:

Association named 'photos' was not found on Article; perhaps you misspelled it?
Association named 'author' was not found on Album; perhaps you misspelled it?
@pokonski
Copy link
Member

pokonski commented Feb 4, 2016

This isn't the right place to ask about it, as it's totally unrelated to PublicActivity. Try Rails discussion groups or google for solutions, it's a common problem.

quick googling suggests:
http://blog.animascodelabs.com/2014/10/30/preloading-polymorphic-relationships-in-rails/
http://makandracards.com/makandra/28347-eager-loading-polymorphic-associations

@pokonski pokonski closed this as completed Feb 4, 2016
@rutger1140
Copy link

I was looking for the same but couldn't quite figure it out (even after searching). Adding just .includes(:trackable) fixes the n+1 issue which I will use for now. @rstacruz did you find a proper fix for this?

@rstacruz
Copy link
Author

.includes(:trackable) is correct, but I never found a way to eager load
second level associations like .includes(trackable: [:owner]).

On Monday, February 22, 2016, Rutger Laurman notifications@github.com
wrote:

I was looking for the same but couldn't quite figure it out (even after
searching). Adding just .includes(:trackable) fixes the n+1 issue which I
will use for now. @rstacruz https://github.com/rstacruz did you find a
proper fix for this?


Reply to this email directly or view it on GitHub
#251 (comment)
.

@jjf21
Copy link

jjf21 commented Jun 26, 2023

Did anyone solve this problem ? include second level associations is not working for me neither ?
Thanks

@jjf21
Copy link

jjf21 commented Oct 5, 2023

Just came back on this topic after while, if someone needs help, here is something that worked for me:

PublicActivity::Activity
   .includes(:trackable)
   .preload(trackable: [
       users: {avatar_attachment: :blob},
       ...
   ])

Good luck !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants