title: how to query associations with a has_many :through
body: <p>I have a Rails app with a has_many :through association between User.rb and Practice.rb, with PracticeListing.rb as a join model.</p>
  
  <p>User.rb</p>
  
  <pre><code>  has_many :practice_listings
    has_many :practices, through: :practice_listings
  </code></pre>
  
  <p>Practice.rb</p>
  
  <pre><code>has_many :practice_listings
  has_many :users, through: :practice_listings
  </code></pre>
  
  <p>PracticeListing.rb</p>
  
  <pre><code>  belongs_to :practice
    belongs_to :user
  </code></pre>
  
  <p>In one of the controllers, I call this scope method on <code>user.rb</code>, passing in the practice_id</p>
  
  <pre><code> scope :lawyers_by_practice, lambda {|practice_id|
    joins(:practices).
    where( users: {practice_id: practice_id},
           users: {lawyer: true},)
  
    }
  </code></pre>
  
  <p>the query from the logs which shows that practice_id is not being used</p>
  
  <pre><code>User Load (1.1ms)  SELECT "users".* FROM "users" INNER JOIN "practice_listings" ON "practice_listings"."user_id" = "users"."id" INNER JOIN "practices" ON "practices"."id" = "practice_listings"."practice_id" WHERE "users"."lawyer" = 't' AND (reputation IS NOT NULL) ORDER BY reputation DESC
  </code></pre>
  
  <p>Can you explain how I should have written that scope method to get the desired results?</p>
  
  <p>With the current model set up, I could do <code>user.practice_ids</code> for a certain user and get an array of the practice_ids ['2','4']</p>
  
  <p>Update</p>
  
  <p>I tried this way (without joining :practices) in the hopes that the query would select only the users with the relevant practice_id, but it returned every user in the db, even those who didn't have a practice</p>
  
  <pre><code> scope :lawyers_by_practice, lambda {|practice_id|
    where( users: {practice_id: practice_id},
           users: {lawyer: true},)
  
    }
  </code></pre>
  
  <p>I also tried this way (by joining :practice_listings instead) but it returned entries for every practice_listing, again ignoring the fact that I only wanted use who had a certain practice id</p>
  
  <pre><code>scope :lawyers_by_practice, lambda {|practice_id|
      joins(:practice_listings).
    where( users: {practice_id: practice_id},
           users: {lawyer: true},)
  
    }
  </code></pre>