title: Rails Query: Filter by properties in another table
body: <p>I'm seeking a clear Rails 4 example on how to filter records based on data associated to them via another table.</p>
  
  <p>Suppose I have a Users model and a Comments model. A User <code>has_many</code> comments, and a Comment <code>belongs_to</code> a user. A comment also has a <code>score</code> column in its table. </p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :comments
  end
  </code></pre>
  
  <p> </p>
  
  <pre><code> Users
  | id  | name    | email               |
  |-----|---------|---------------------|
  | 1   | "Alice" | "alice@example.com" |
  | 2   | "Bob"   | "bob@example.com"   |
  | ...                                 |
  </code></pre>
  
  <p> </p>
  
  <pre><code>class Comment &lt; ActiveRecord::Base
    belongs_to :user
  end 
  
   Comments
  | id  | score | content          | user_id |
  |-----|-------|------------------|---------|
  | 1   | 0     | "lol"            | 2       |
  | 2   | 2     | "more like love" | 3       |
  | ...                                      |
  </code></pre>
  
  <p>How would I obtain all users that have made a comment with the content "k" that has a score > 0? Note that what I want to return is the Users, not the Comments.</p>
  
  <hr>
  
  <p>Also, consider a more complex example, where a User <code>has_many</code> comments and likes, Comments <code>belong_to</code> a user, and a Comment <code>has_many</code> Likes. Likes <code>belong_to</code> a User and <code>belong_to</code> a Comment. Note that <code>score</code> is no longer a factor in this example.</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :comments
    has_many :likes
  end
  </code></pre>
  
  <p> </p>
  
  <pre><code> Users
  | id  | name    | email               |
  |-----|---------|---------------------|
  | 1   | "Alice" | "alice@example.com" |
  | 2   | "Bob"   | "bob@example.com"   |
  | ...                                 |
  </code></pre>
  
  <p> </p>
  
  <pre><code>class Comment &lt; ActiveRecord::Base
    belongs_to :user
    has_many :likes
  end
  </code></pre>
  
  <p> </p>
  
  <pre><code> Comments
  | id  | content          | user_id |
  |-----|------------------|---------|
  | 1   | "lol"            | 2       |
  | 2   | "more like love" | 3       |
  | ...                              |
  </code></pre>
  
  <p> </p>
  
  <pre><code>class Like &lt; ActiveRecord::Base
    belongs_to :user
    belongs_to :comment
  end
  </code></pre>
  
  <p> </p>
  
  <pre><code> Likes
  | id  | user_id | comment_id |
  |-----|---------|------------|
  | 1   | 1       | 2          |
  | 2   | 4       | 3          |
  | ...                        |
  </code></pre>
  
  <p>In this second example, how would I find all the Users who have ever had one of their comments liked by the User named 'Fonzie'?</p>