Note that there are some explanatory texts on larger screens.

plurals
  1. POPreload association when called from model's method
    text
    copied!<p>Suppose I have this simple app working :</p> <pre><code># model class Project has_many :numbers def my_numbers numbers end end # controller class ProjectController def index @projects = Project.includes(:numbers) end end </code></pre> <p>Within my first view, no problem. I'm calling the association directly, so all numbers have already been loaded.</p> <pre><code>@projects.each do |project| project.numbers # no probleme here. Hit the cache of included numbers. end </code></pre> <p>And here is the log</p> <pre><code>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) </code></pre> <p>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:</p> <pre><code>@projects.each do |project| project.my_numbers end </code></pre> <p>And here is the log</p> <pre><code>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 </code></pre> <p>Is there anyway to avoid that? Why does my model not reusing the included numbers from the first db request?</p> <p>Thanks in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload