title: Active record query using associated model scope
body: <p>model <code>Food</code> has many <code>Requests</code></p>
  <pre class="lang-rb prettyprint-override"><code>class Food &lt; ActiveRecord::Base
    has_many :requests
    # scope :where_has_requests, -&gt; { includes(:requests).where.not(requests: { id: nil }) }
  end
  </code></pre>
  <p><code>Requests</code> may belong to <code>User</code></p>
  <pre class="lang-rb prettyprint-override"><code>class Request &lt; ActiveRecord::Base
    # belongs_to :giver, class_name: 'User'
    # belongs_to :receiver, class_name: 'User'
    scope :where_belongs_to, -&gt;(user) { where(giver_id: user.id ).or(where(receiver_id: user.id)) }
  end
  </code></pre>
  <p>How to query <code>Food</code> that has <code>Requests</code> which belongs to given <code>User</code> using Request scope?</p>
  <pre class="lang-rb prettyprint-override"><code>Food.joins(:requests).where(&quot;requests.giver_id=#{user.id} OR requests.receiver_id=#{user.id}&quot;)
  </code></pre>
  <p>I've been thinking about this one:</p>
  <pre class="lang-rb prettyprint-override"><code>Food.joins(:requests).where(requests.where_belongs_to(user))
  </code></pre>
  <p>But I'm lost. Any idea?</p>
  <h1>Notice</h1>
  <p>I have seen <a href="https://stackoverflow.com/questions/43209400/rails-querying-an-associated-models-scope">Rails querying an associated models scope</a> <strong>before</strong> I've post this question, though I cannot understand it quite well and I think the cases are different somehow.</p>