Reputation: 2119
So i've been struggling with this for a few hours and im hoping someone can help.
I have a 3 level relationship, List, Page & App.
A List has_many Pages
A Page belongs_to List and can optionally belongs_to an App.
App has_many Pages
With a query like this
@account.lists.includes(pages: :app)
Everything works fine, I have no N+1 queries, and its all being eager loaded correctly
Eg
List Load (3.0ms) SELECT `lists`.* FROM `rotations` WHERE `lists`.`account_id` = 1
Page Load (2.5ms) SELECT `pages`.* FROM `pages` WHERE `pages`.`list_id` IN (13, 17, 18)
App Load (2.0ms) SELECT `apps`.* FROM `apps` WHERE `apps`.`id` IN (6, 9, 15)
My problem is that all these statements are SELECT * FROM
although the Apps records in particular are quite heavy. There can be entire HTML documents in a column named "content"
I really need to be able to only SELECT apps.id, apps.name FROM
apps ....`. So im not loading these full objects into memory only just discard it all a moment later when I render only the ID and names.
I would perform this manually, although I can't seem to get this working with ActiveModelSerializers.
My serializers are pretty standard. A List that has_many :pages and a page that belongs_to :app.
How can I only pull select attributes from one of my nested associations? Im pretty sure I can use joins()
but im not sure how that works with my serializers?
Cheers
Upvotes: 0
Views: 1535
Reputation: 6411
Hmmm.. trying to test this on an app with similar associations. I think something like this might work:
@account.lists.includes(pages: :app).pluck("apps.id", "apps.name")
This will do a LEFT OUTER JOIN on the associations.
@account.lists.joins(pages: :app).pluck("apps.id", "apps.name")
will do INNER JOINS. Not sure what you are looking for exactly without a lot more info on your data structures and example output.
Upvotes: 1