Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing LEFT OUTER JOIN to eager load associations without conditions?
    primarykey
    data
    text
    <p>We have a model with a has_one association set up:</p> <pre><code>class User has_one :shirt class Shirt belongs_to :user </code></pre> <p>At the moment we can add <code>.includes(:shirt)</code> when retrieving a limited array of Users and it will conduct two SQL queries as expected.</p> <p>The problem for us is that the query to load the pages is doing this:</p> <pre><code>SELECT "shirt".* FROM "shirts" WHERE "shirt"."user_id" IN (2147521, 2147522 ... ) </code></pre> <p>When retrieving, say, 50 Users and Shirts this isn't very performant for us. Our users and shirts tables are big. We're noticing a big speed increase by forcing Rails to use an INNER JOIN instead by doing:</p> <pre><code>User.where( ... ).joins(:shirts).includes(:shirts).limit(50) </code></pre> <p>Unfortunately this only returns users that have shirts. We need to be able to return a limited array of users whether they have an associated shirt or not.</p> <p>Is there a way to force Rails to eager load associated objects using a LEFT OUTER JOIN instead of the two-query method that is the default?</p> <h2>Edit</h2> <p>By adding a <code>where</code> clause that returns true whether a value on the associated object is null or not. It doesn't seem to mind if there's no associated object, at least on Postgres.</p> <pre><code>User.where( ... ).includes(:shirt).where("shirts.created_at IS NULL OR shirts.created_at IS NOT NULL") </code></pre> <p>This solves the problem but it's hardly ideal, isn't there a way to use LEFT OUTER JOIN instead of the default two-query approach?</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.
 

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