Preload association when called from model's method
Suppose I have this simple app working :
# model
class Project
has_many :numbers
def my_numbe开发者_开发知识库rs
numbers
end
end
# controller
class ProjectController
def index
@projects = Project.includes(:numbers)
end
end
Within my first view, no problem. I'm calling the association directly, so all numbers have already been loaded.
@projects.each do |project|
project.numbers
# no probleme here. Hit the cache of included numbers.
end
And here is the log
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)
But with this second example, calling numbers from within a method call in Project, each call to my_numbers triggers a new db call, as you can see below:
@projects.each do |project|
project.my_numbers
end
And here is the log
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
Is there anyway to avoid that? Why does my model not reusing the included numbers from the first db request?
Thanks in advance!
I have tried this code in Rails 3.0.9 and it does not do the behavior you describe. Are you sure Numbers are not triggering a callback?
精彩评论