<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pierre Yager on Medium]]></title>
        <description><![CDATA[Stories by Pierre Yager on Medium]]></description>
        <link>https://medium.com/@zedalaye?source=rss-34c7d627e638------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*58bbV1KmRdTsxdK6.jpg</url>
            <title>Stories by Pierre Yager on Medium</title>
            <link>https://medium.com/@zedalaye?source=rss-34c7d627e638------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:20:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zedalaye/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build crazy queries with ActiveRecord and Arel]]></title>
            <link>https://medium.com/@zedalaye/build-crazy-queries-with-activerecord-and-arel-e7bd3b606324?source=rss-34c7d627e638------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7bd3b606324</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Pierre Yager]]></dc:creator>
            <pubDate>Tue, 25 Jul 2017 23:25:53 GMT</pubDate>
            <atom:updated>2017-08-17T15:42:28.503Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Today I have had to fix a rather complex query. Turned into plain old SQL it rendered as :</p><pre>SELECT products.* FROM products<br>WHERE EXISTS (<br>  SELECT prices.* FROM prices<br>  WHERE prices.country_code IN [&#39;FR&#39;, &#39;DE&#39;] AND <br>        prices.customer_price &gt; 0 AND<br>        current_date BETWEEN(<br>          COALESCE(prices.valid_from, &#39;yesterday&#39;::DATE) <br>      and COALESCE(prices.valid_to, &#39;tomorrow&#39;::DATE)<br>        ) AND<strong><br>        </strong>prices.product_id = products.id<br>)</pre><p>The goal here is to display products when they have, at least, an active (valid at current_date), positive customer_price.</p><p>The model Price looks like:</p><pre>class Price &lt; ApplicationRecord<br>  belongs_to :product</pre><pre>  scope :active, -&gt; {<br>    <em>where </em>&lt;&lt;~SQL<br>      current_date BETWEEN <br>        coalesce(&quot;prices&quot;.valid_from, &#39;yesterday&#39;::DATE) <br>    AND coalesce(&quot;prices&quot;.valid_to, &#39;tomorrow&#39;::DATE)<br>    SQL<br>  }<br>  scope :defined, -&gt;(country, level) {<br>    <em>where</em>(country_code: <em>countries</em>).<br>    <em>where</em>(&quot;\&quot;prices\&quot;.#{<em>level</em>.to_s}_price &gt; 0&quot;).<br>    active<br>  }<br>end</pre><p>And the model Product resembles:</p><pre>class Product &lt; ApplicationRecord<br>  has_many :prices</pre><pre>  scope :with_active_price, -&gt;(<em>company</em>, <em>country</em>, <em>level</em>) {<br>    countries = [ <em>country</em>, <em>company</em>.default_country ]<br>    <em>where</em>( <br>      Price.defined(countries, level)<br>           .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>           .exists <br>    )<br>  }<br>end</pre><p>The query at top can now be generated using ActiveRecord using:</p><pre>Product.with_active_price(Company.find(1), ‘FR’, :customer)</pre><p>But today my customer found that it cannot deactivate a product by setting its Price attributes to 0 when a Price exists for the Company#default_country (because countries are mixed in a single array).</p><p>The query able to fix that problem is more complex :</p><pre><strong>SELECT </strong>&quot;products&quot;.* <strong>FROM </strong>&quot;products&quot;<br><strong>WHERE </strong><em>EXISTS</em>(<br>  <strong>SELECT * FROM </strong>&quot;prices&quot;<br>  <strong>WHERE </strong>&quot;prices&quot;.&quot;country_code&quot; = &#39;FR&#39; <strong>AND<br>        </strong>&quot;prices&quot;.&quot;customer_price&quot; &gt; 0 <strong>AND<br>        </strong><em>current_date </em><strong>BETWEEN <br>          </strong><em>COALESCE</em>(&quot;prices&quot;.&quot;valid_from&quot;, &#39;yesterday&#39;::DATE) <br>      <strong>AND </strong><em>COALESCE</em>(&quot;prices&quot;.&quot;valid_to&quot;, &#39;tomorrow&#39;::DATE) <strong>AND<br>        </strong>&quot;prices&quot;.&quot;product_id&quot; = &quot;products&quot;.&quot;id&quot;<br>  ) <strong>OR (<br>    NOT </strong><em>EXISTS</em>(<br>  <strong>SELECT * FROM </strong>&quot;prices&quot;<br>  <strong>WHERE </strong>&quot;prices&quot;.&quot;country_code&quot; = &#39;FR&#39; <strong>AND<br>         </strong><em>current_date </em><strong>BETWEEN <br>           </strong><em>COALESCE</em>(&quot;prices&quot;.&quot;valid_from&quot;, &#39;yesterday&#39;::DATE) <br>       <strong>AND </strong><em>COALESCE</em>(&quot;prices&quot;.&quot;valid_to&quot;, &#39;tomorrow&#39;::DATE) <strong>AND<br>         </strong>&quot;prices&quot;.&quot;product_id&quot; = &quot;products&quot;.&quot;id&quot;<br>    ) <strong>AND </strong><em>EXISTS</em>(<br>  <strong>SELECT * FROM </strong>&quot;prices&quot;<br>  <strong>WHERE </strong>&quot;prices&quot;.&quot;country_code&quot; = &#39;DE&#39; <strong>AND    <br>        </strong>&quot;prices&quot;.&quot;distributor_price&quot; &gt; 0 <strong>AND                 <br>        </strong><em>current_date </em><strong>BETWEEN <br>          </strong><em>COALESCE</em>(&quot;prices&quot;.&quot;valid_from&quot;, &#39;yesterday&#39;::DATE) <br>      <strong>AND </strong><em>COALESCE</em>(&quot;prices&quot;.&quot;valid_to&quot;, &#39;tomorrow&#39;::DATE) <strong>AND<br>        </strong>&quot;prices&quot;.&quot;product_id&quot; = &quot;products&quot;.&quot;id&quot;<br>  )<br>)</pre><p>… and a bit… hard, if not impossible to write using pure ActiveRecord, so I gave a try to Arel. Given that the only source of examples of complex use of Arel is the ActiveRecord source code himself, I think that my discoveries may help.</p><p>The game here is to merge 3 similar subqueries using OR and AND.</p><p>Something like:</p><pre>SELECT * FROM products WHERE q1 OR (q2 AND q3)</pre><p>To generate these subqueries we need a reference to the Price “Arel Table”:</p><pre>price = Price.arel_table</pre><p>Then, we should rewrite the BETWEEN clause using Arel so we will be able to reuse it :</p><pre>valid_from = Arel::Nodes::<strong>NamedFunction</strong>.new(&#39;COALESCE&#39;, [<br>  price[:valid_from], <br>  Arel.<strong>sql</strong>(&quot;&#39;yesterday&#39;::DATE&quot;)<br>])<br>valid_to = Arel::Nodes::<strong>NamedFunction</strong>.new(&#39;COALESCE&#39;, [ <br>  price[:valid_to], <br>  Arel.<strong>sql</strong>(&quot;&#39;tomorrow&#39;::DATE&quot;)<br>])<br>between = Arel::Nodes::<strong>Between</strong>.new(<br>  Arel.<strong>sql</strong>(&#39;current_date&#39;), <br>  valid_from.<strong>and</strong>(valid_to)<br>)</pre><p>Easy, no? Raw SQL is escaped using Arel.sql(), references to fields are obtained using arel_table#[]. Between is already an Arel::Nodes::Node but SQL function COALESCE is not defined however we can easily wrap it within an Arel::Nodes::NamedFunction.</p><p>Then we rewrite the 3 subqueries (arel_table[:id] refers to “self” which is the Product class) :</p><pre>select = Arel::<strong>SelectManager</strong>.new(<br>  Price.arel_engine, Price.arel_table<br>)<br>q1 = select.where(price[:country_code].<strong>eq</strong>(country_code))<br>           .where(price[&quot;#{price_level}_price&quot;].<strong>gt</strong>(0))<br>           .where(<strong>between</strong>)<br>           .where(price[:product_id].<strong>eq</strong>(arel_table[:id]))<br>           .<strong>exists</strong></pre><pre>select = Arel::<strong>SelectManager</strong>.new(<br>  Price.arel_engine, Price.arel_table<br>)<br>q2 = select.where(price[:country_code].<strong>eq</strong>(country_code))<br>           .where(<strong>between</strong>)<br>           .where(price[:product_id].<strong>eq</strong>(arel_table[:id]))<br>           .<strong>exists</strong>.<strong>not</strong></pre><pre>select = Arel::<strong>SelectManager</strong>.new(<br>  Price.arel_engine, Price.arel_table<br>)<br>q3 = select.where(price[:country_code].<br>                    <strong>eq</strong>(company.default_country))<br>           .where(price[&quot;#{price_level}_price&quot;].<strong>gt</strong>(0))<br>           .where(<strong>between</strong>)<br>           .where(price[:product_id].<strong>eq</strong>(arel_table[:id]))<br>           .<strong>exists</strong></pre><p>(You are right, I should refactor theses blocs into a builder method/class…) and finally we can mix these 3 queries together using OR and ANDs:</p><pre>where(q1.<strong>or</strong>(q2.<strong>and</strong>(q3)))</pre><p>The key here was to use Arel::SelectManager (like ActiveRecord do!) to be able to transform the final subqueries into “[NOT] EXISTS()” clauses.</p><p>What about ActiveRecord ? Why was it so complex to fix original code ?</p><p>Calling “exists” on an ActiveRecord::Relation transforms that relation into an Arel AST, so that *should* do the trick:</p><pre>scope :with_active_price, -&gt;(<em>company</em>, <em>country</em>, <em>level</em>) {<br>  q1 = Price.defined(countries, level)<br>            .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>            .exists <br>  q2 = Price.not_defined(countries)<br>            .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>            .exists.not<br>  q3 = Price.defined(<em>company</em>.default_country, <br>                     <em>price_level</em>)<br>            .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>            .exists<br>  where(q1.or(q2.and(q3)))<br>}</pre><p>But that don’t work because params assigned in Price.defined() scope are not retained into the Arel AST and when the query is executed, it misses these params.</p><p>Because the error message looks furiously like <a href="https://github.com/rails/rails/issues/20077">https://github.com/rails/rails/issues/20077</a> I checked if I could give a try to the trick consisting in transforming subqueries to SQL and assembles them as a string at the end.</p><pre>scope :with_active_price, -&gt;(<em>company</em>, <em>country</em>, <em>level</em>) {<br>  q1 = Price.defined(countries, level)<br>            .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>            .exists<br>            <strong>.to_sql</strong><br>  q2 = Price.not_defined(countries)<br>            .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>            .exists.not<br>            .<strong>to_sql</strong><br>  q3 = Price.defined(<em>company</em>.default_country, <br>                     <em>price_level</em>)<br>            .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>            .exists<br>            .<strong>to_sql</strong><br>  <em>where</em>(<strong>&quot;</strong>{q1}<strong> or (</strong>#{q2} <strong>and</strong> #{q3}<strong>)&quot;</strong>)<br>}</pre><p>I get this error (translated from French):</p><pre>PG::UndefinedFunction (ERROR:  operator does not exists : character varying = integer<br>LINE 1: ...es&quot;.* FROM &quot;prices&quot; WHERE &quot;prices&quot;.&quot;country_code&quot; = $1 AND (...<br>                                                             ^<br>HINT:  No operator correspond to the given name and argument types.<br>You should add explicit type conversions.</pre><p>I finally found a way by transforming intermediate subqueries and build EXISTS () or (NOT EXISTS () and EXISTS()) manually.</p><pre>scope :with_active_price, -&gt;(<em>company</em>, <em>country</em>, <em>level</em>) {<br>  q1 = Price.defined(countries, level)<br>            .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>            .<strong>to_sql</strong><br>  q2 = Price.not_defined(countries)<br>            .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>            .<strong>to_sql</strong><br>  q3 = Price.defined(<em>company</em>.default_country, <br>                     <em>price_level</em>)<br>            .<em>where</em>(&#39;&quot;prices&quot;.product_id = &quot;products&quot;.id&#39;)<br>            .<strong>to_sql</strong><br>  <em>where</em>(<strong>&quot;EXISTS (</strong>#{q1}<strong>) or (NOT EXISTS(</strong>#{q2}<strong>) and EXISTS(</strong>#{q3}<strong>))&quot;</strong>)<br>}</pre><p>Finally I think this way the code is more compact and maybe more explicit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7bd3b606324" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>