-
Notifications
You must be signed in to change notification settings - Fork 108
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
Eager loading issue #165
Comments
It's obvious that the problem originates from |
Not necessarly, a simple representer like this will also trigger N+1 queries: module SkillModerationsRepresenter
include Roar::JSON
property :foo, getter: proc { to_a.map(&:author).uniq }
property :bar, getter: proc { to_a.map(&:author).uniq }
end |
Let's go the other way round: What happens when you do |
Nevermind, I found that this does not work as I would expect: tasks = SkillModeration.all.includes(:author)
tasks.map(&:author)
tasks.map(&:author) First time, it uses the eager loaded authors, second time, it performs the N+1 queries... So it's not related to representable. |
Pheew... 😜 Isn't the whole point of |
Yes :) I just found an open issue for this :) https://jira.mongodb.org/browse/MONGOID-3942 For futur readers, use tasks = Task.all.includes(:author).cache
tasks.map(&:author)
tasks.map(&:author) Thanks man for guidance ;) |
Figured it would be easier to discuss about the issue here. Here is a recap of my issue.
The issue is that when I try to represent a collection of
SkillModeration
resources, I need to eager load theAuthor
resource to avoid N+1 queries. Here I'm using mongoid but it would be the exact same thing with activerecord.Now if we look at the queries generated we see that it performed the eager loading query but also all the N+1 queries.
The eager loading query:
The N+1 queries as well:
I found that it's because of this code:
which calls the
to_a
method twice. If we were in anirb
console, it would not be an issue. For example, in a console, you can do this and it won't perform the N+1 queries:But for some reasons, on a representer object, it triggers the N+1 queries. If for example, you remove the
included
, the representer class would look like this:then calling
tasks.to_json
generates only the eager loading query but not all the N+1.So the issue seems to come from how
representable
uses thesource
(the collection). Calling multiple times thesource
(to_a
) inside the representer cause the eager loading to work only once.I have no idea how the
source
is used in the gem, that's why i'm posting this issue. Hope you can help me to figure out what's going on here. It's pretty easy to reproduce, using AR or mongoid.Thanks
The text was updated successfully, but these errors were encountered: