Note that there are some explanatory texts on larger screens.

plurals
  1. POActiveRecord requerying depending on order of operations
    primarykey
    data
    text
    <p>New to Ruby and Rails so forgive me if my terminology is off a bit.</p> <p>I am working on optimizing some inherited code and watching the logs I am seeing queries repeat themselves due to lines like this in a .rabl file:</p> <pre class="lang-rb prettyprint-override"><code>node(:program) { |user| (!user.programs.first.nil?) ? user.programs.first.name : '' } </code></pre> <p><code>user</code> and <code>program</code> are both active record objects </p> <p>Moving to the rails console, I can replicate the problem, but I can also get the expected behavior, which is only one query:</p> <pre><code>&gt;u = User.find(1234) User Load (0.3ms) SELECT `users`.* FROM `users` WHERE [...] &gt; (!u.programs.first.nil?) ? u.programs.first.name : '' Program Load (0.2ms) SELECT `programs`.* FROM `programs` [...] Program Load (0.3ms) SELECT `programs`.* FROM `programs` [...] =&gt; "Output" </code></pre> <p>Note that repeating the ternary statement in the console will <em>always</em> give me 2 queries.</p> <p>I can get the expected behavior like so:</p> <pre><code>&gt; newu = User.find(12345) User Load (3.8ms) SELECT `users`.* FROM `users` WHERE [...] &gt; newu.programs Program Load (0.6ms) SELECT `programs`.* FROM `programs` [...] &gt; (!newu.programs.first.nil?) ? newu.programs.first.name : '' =&gt; "Output" </code></pre> <p>Repeating the ternary statement now won't requery at all.</p> <p>So the question is: why does calling <code>newu.programs</code> change the behavior? Shouldn't calling <code>u.programs.first.nil?</code> also act to load all the program records in the same way? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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