TIL: Pass in an ActiveRecord Object to a where string
<p>I’m surprised I didn’t already know this, but if you have an ActiveRecord <code>where</code> statement that references an id column, you can just pass in an object and it will pass in the object’s id, not the string representation of the object.</p> <div class="highlight"><pre class="highlight ruby"><code><span class="n">company</span> <span class="o">=</span> <span class="no">Company</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="s2">"users.company_id = ?"</span><span class="p">,</span> <span class="n">company</span><span class="p">)</span> <span class="c1"># is equal to</span> <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="s2">"users.company_id = ?"</span><span class="p">,</span> <span class="n">company</span><span class="p">.</span><span class="nf">id</span><span class="p">)</span> </code></pre></div> <p>So when you create named scopes, you don’t have to do the song-and-dance where you check to see if the object is a model or an integer, as shown below.</p> <div class="highlight"><pre class="highlight ruby"><code><span class="n">scope</span> <span class="ss">:by_company</span><span class="p">,</span> <span class="nb">lambda</span> <span class="p">{</span> <span class="o">|</span><span class="n">company</span><span class="o">|</span> <span class="n">company_id</span> <span class="o">=</span> <span class="n">company</span><span class="p">.</span><span class="nf">is_a?</span><span class="p">(</span><span class="no">Company</span><span class="p">)</span> <span class="p">?</span> <span class="n">company</span><span class="p">.</span><span class="nf">id</span> <span class="p">:</span> <span class="n">company</span> <span class="n">where</span><span class="p">(</span> <span class="s2">"users.company_id = ?"</span><span class="p">,</span> <span class="n">company_id</span> <span class="p">)</span> <span class="p">}</span> <span class="p">}</span> <span class="c1"># You wouldn't actually want to use a string in this example.</span> <span class="c1"># Try to only use strings in very complex scopes and queries.</span> </code></pre></div>