从模型方法调用时预加载关联

时间:2011-08-31 16:19:06

标签: ruby-on-rails ruby-on-rails-3

假设我有这个简单的应用程序:

# model
class Project
    has_many :numbers

  def my_numbers
    numbers
  end
end

# controller
class ProjectController
  def index
    @projects = Project.includes(:numbers)
  end  
end

在我的第一个视图中,没问题。我正在直接调用该关联,因此所有数字都已加载。

@projects.each do |project|
  project.numbers
  # no probleme here. Hit the cache of included numbers.
end

这是日志

Project Load (0.8ms)  SELECT "projects".* FROM "projects" 
ProjectNumber Load (0.5ms)  SELECT "project_numbers".* FROM "project_numbers" WHERE "project_numbers"."project_id" IN (1,2)

但是在第二个例子中,在Project中的方法调用中调用数字,每次调用my_numbers都会触发一个新的db调用,如下所示:

@projects.each do |project|
  project.my_numbers
end

这是日志

Project Load (0.8ms)  SELECT "projects".* FROM "projects" 
ProjectNumber Load (0.5ms)  SELECT "project_numbers".* FROM "project_numbers" WHERE "project_numbers"."project_id" IN (1,2)
ProjectNumber Load (0.5ms)  SELECT "project_numbers".* FROM "project_numbers" WHERE "project_numbers"."project_id" = 1
ProjectNumber Load (0.5ms)  SELECT "project_numbers".* FROM "project_numbers" WHERE "project_numbers"."project_id" = 2

有没有避免这种情况?为什么我的模型不重用第一个db请求中包含的数字?

提前致谢!

1 个答案:

答案 0 :(得分:1)

我在Rails 3.0.9中尝试过这段代码,并没有按照你描述的行为进行操作。你确定Numbers没有触发回调吗?