Note that there are some explanatory texts on larger screens.

plurals
  1. POScope with join on :has_many :through association
    text
    copied!<pre><code>class Users &lt; ActiveRecord::Base has_many :meetings, :through =&gt; :meeting_participations has_many :meeting_participations end class Meetings &lt; ActiveRecord::Base has_many :users, :through =&gt; :meeting_participations has_many :meeting_participations end class MeetingParticipations &lt; ActiveRecord::Base belongs_to :user belongs_to :meeting scope :hidden, where(:hidden =&gt; true) scope :visible, where(:hidden =&gt; false) end </code></pre> <p><code>hidden</code> is an extra boolean column within the m2m association table. Given some <code>Users</code> instance <code>current_user</code>, I want to do</p> <pre><code>current_user.meetings.visible </code></pre> <p>which will retrieve a collection of <code>Meetings</code> for which the user is a participant where the <code>hidden</code> column is <code>false</code>. The closest I have gotten is adding the following scope to the <code>Meetings</code> class</p> <pre><code>scope :visible, joins(:meeting_participations) &amp; MeetingParticipation.visible </code></pre> <p>The <code>scope</code> does filter the <code>Meetings</code> against the <code>MeetingParticipations</code> table, however there is no join/condition against the <code>MeetingParticipations</code> table related to <code>current_user</code>.</p> <p>The issue with this is, if <code>current_user</code> and <code>another_user</code> are both participants for some <code>Meetings</code> instance, a <code>Meetings</code> record in the result set will be returned for each participant that has <code>hidden</code> set to <code>false</code>. If <code>current_user</code> has <code>true</code> set for <code>hidden</code> for all <code>Meetings</code>, if <code>another_user</code> is a participant in any of those same Meetings with <code>hidden</code> set to <code>false</code>, those <code>Meetings</code> will appear in the <code>Meetings.visible</code> result set.</p> <p>Is it possible to have a scope as I've mentioned above which will properly join on the <code>User</code> instance? If not, can someone recommend a solution to this?</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