Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In rails the <code>joins(:symbol)</code> statement turns into an inner join which is not suited for finding relations that don't exist. You can write the join by hand in order to make it a left join:</p> <pre><code>Cause.joins(""" LEFT JOIN cause_user_memberships ON cause_user_memberships.cause_id = causes.id AND cause_user_memberships.user_id = #{current_user.id} """).where("cause_user_memberships.id IS NULL") </code></pre> <p><strong>UPDATED</strong></p> <p>The inner join will prevent the creation of a set of Causes that don't have a mapping to the given user. For example:</p> <pre><code>Causes id | name ============ 1 | Cause 1 2 | Cause 2 Users id | name ============ 1 | User 1 Cause User Memberships id | user_id | cause_id ======================= 1 | 1 | 1 SELECT * FROM causes INNER JOIN cause_user_memberships ON cause_user_memberships.cause_id = causes.id AND cause_user_memberships.user_id = 1 </code></pre> <p>Will return</p> <pre><code>causes.id | causes.name | cause_user_memberships.id | cause_user_memberships.user_id | cause_user_memberships.cause_id =========================================================================================================================== 1 | Cause 1 | 1 | 1 | 1 </code></pre> <p>Which you can't perform any more logic on in order to tease out the causes the user doesn't belong to.</p> <pre><code>SELECT * FROM causes LEFT JOIN cause_user_memberships ON cause_user_memberships.cause_id = cause.id AND cause_user_memberships.user_id = 1 </code></pre> <p>Will return</p> <pre><code>causes.id | causes.name | cause_user_memberships.id | cause_user_memberships.user_id | cause_user_memberships.cause_id =========================================================================================================================== 1 | Cause 1 | 1 | 1 | 1 2 | Cause 2 | null | null | null </code></pre> <p>In this case all the Causes will get a row whether they match a record in the <code>cause_user_memberships</code> table or not. Now you can apply additional conditions to tease out the causes the user doesn't belong to (where cause_user_membership.id is null).</p>
 

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