Includes still result in second database query when using constrained column relationship
I'm trying to use includes
in a query to limit the number of subsequent database calls that are fired on rendering, but I also want the included calls to select a subset of columns from related tables. Specifically, I want to get a set of posts, their comments and just the name of the user who wrote each comment.
So I added
belongs_to :user
belongs_to :user_for_display, :select => "users.id, user.name", :class_name => "User", :foreign_key => "user_id"
to my comment model.
From the console when I do
p = Post.where(:id => 1).includes(comments: [:user_for_display])
I can see that the correct requests are firing:
SELECT posts.* FROM posts WHERE posts.id = 1
SELECT comments.* FROM comments comments.attachable_type = "Post" AND comments.attachable_id IN (1)
SELECT users.id, users.name FROM users WHERE users.id IN (1,2,3)
but call
p.first.comments.first.user.name
still results in a call to a full database load:
User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 11805 LIMIT 1
=> "John"
The link only p.first.comments
does not trigger a second request for comments. And if I include the full relation :user
instead :user_for_display
, the call to get the username does not trigger a second user request (but I would rather not load the full user record).
Can SELECT be used to limit fields in include?
source to share