Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The canonical way to do this with Rails 3:</p> <pre><code>Foo.includes(:bar).where("bars.id IS NOT NULL") </code></pre> <p>ActiveRecord 4.0 and above adds <a href="http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions" rel="noreferrer"><code>where.not</code></a> so you can do this:</p> <pre><code>Foo.includes(:bar).where.not('bars.id' =&gt; nil) Foo.includes(:bar).where.not(bars: { id: nil }) </code></pre> <p>When working with scopes between tables, I prefer to leverage <a href="http://api.rubyonrails.org/classes/ActiveRecord/SpawnMethods.html#method-i-merge" rel="noreferrer"><code>merge</code></a> so that I can use existing scopes more easily.</p> <pre><code>Foo.includes(:bar).merge(Bar.where.not(id: nil)) </code></pre> <p>Also, since <a href="http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-includes" rel="noreferrer"><code>includes</code></a> does not always choose a join strategy, you should use <a href="http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-references" rel="noreferrer"><code>references</code></a> here as well, otherwise you may end up with invalid SQL.</p> <pre><code>Foo.includes(:bar) .references(:bar) .merge(Bar.where.not(id: nil)) </code></pre> <p>I no longer recommend using <a href="https://github.com/activerecord-hackery/squeel" rel="noreferrer">Squeel</a> for this as it doesn't always have a full-time maintainer, and it depends on private APIs that cause frequent breaking changes.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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