belongs_to association loaded individually even after eager loading

假如想象 提交于 2019-12-22 10:57:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!