【问题标题】:belongs_to association loaded individually even after eager loadingbelongs_to 关联即使在急切加载后也单独加载
【发布时间】:2013-07-03 14:53:41
【问题描述】:

我有以下关联

class Picture < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :pictures
end

在我的 PicturesController 中,我渴望加载用户

class PicturesController < ApplicationController
  def index
    @pictures = Picture.includes(:user).all
  end
end

在我看来,我正在显示每张图片的用户名

-@pictures.each do |picture| 
  %tr
    %td= picture.name
    %td= picture.user.name

现在的问题是,即使我急于加载用户,我看到在视图中显示用户名时触发了个别查询。

我有大约 1000 条图片记录,并且为此请求触发了 1000 多个查询。 我究竟做错了什么?如何避免对用户进行个别查询?

【问题讨论】:

  • 你没有做错任何事 - 就是所有代码吗?
  • 是的。我在控制台中做了一些测试,发现很有趣。当我在控制器中执行 Picture.find(:all, :include =&gt; :user) 并在视图中执行 picture.user["name"] 时,我看不到这些单独的查询
  • 尝试删除 .all 无论如何都不需要(.each 将触发 sql 请求)。您还可以在关联宏上使用 inverse_of 选项。然而罪魁祸首在别处
  • 我发现了这个错误报告rails.lighthouseapp.com/projects/8994/tickets/…。它看起来像 rails 3 中的一个错误。
  • 这仍然是 Rails 3 的问题吗?我正在使用 3.2.21,我遇到了与 @Vimsha 相同的问题。

标签: ruby-on-rails performance ruby-on-rails-3.2 eager-loading


【解决方案1】:

如果您只显示用户名,那么在查询中将其与内部连接一起抓取怎么样?

查询:

@pictures = Picture.select("pictures.*, users.name as user_name").joins(:user).all

查看:

- @pictures.each do |picture| 
  %tr
    %td= picture.name
    %td= picture.user_name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多