问题
I have the below association
class Picture < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :pictures
end
And in my PicturesController i am eager loading the user
class PicturesController < ApplicationController
def index
@pictures = Picture.includes(:user).all
end
end
In my view, i am displaying each pictures user name
-@pictures.each do |picture|
%tr
%td= picture.name
%td= picture.user.name
Now the question is, even though i am eager loading the user, i see individual queries fired while displaying the user name in the view.
I have around 1000 picture records and i have more than 1000 queries fired for this request. What am i doing wrong? How do i avoid individual queries for user?
回答1:
If you're only displaying the user's name, how about grabbing it in the query along with an inner join?
Query:
@pictures = Picture.select("pictures.*, users.name as user_name").joins(:user).all
View:
- @pictures.each do |picture|
%tr
%td= picture.name
%td= picture.user_name
来源:https://stackoverflow.com/questions/17451312/belongs-to-association-loaded-individually-even-after-eager-loading