title: Rails: join with multiple conditions
body: <p>I have a simple model like</p>
  
  <pre><code>class Interest &lt; ActiveRecord::Base
    has_and_belongs_to_many :user_profiles
  end
  
  class UserProfile &lt; ActiveRecord::Base
    has_and_belongs_to_many :interests
  end
  </code></pre>
  
  <p>When I want to query all the users with a specific interests, that's fairly simple doing</p>
  
  <pre><code>UserProfile.joins(:interests).where('interests.id = ?', an_interest)
  </code></pre>
  
  <p>But how can I look for users who have multiple interests? Of course if I do</p>
  
  <pre><code>UserProfile.joins(:interests).where('interests.id = ?', an_interest).where('interests.id = ?', another_interest)
  </code></pre>
  
  <p>I get always an empty result, since after the join, no row can have simultaneously interest.id = an_interest and interest.id = another_interest.</p>
  
  <p>Is there a way in ActiveRecord to express "I want the list of users who have 2 (specified) interests  associated?</p>
  
  <p><strong>update (solution)</strong> that's the first working version I came up, kudos to Omar Qureshi </p>
  
  <pre><code>    specified_interests.each_with_index do |i, idx|
        main_join_clause = "interests_#{idx}.user_profile_id = user_profiles.id"
        join_clause = sanitize_sql_array ["inner join interests_user_profiles interests_#{idx} on
                      (#{main_join_clause} and interests_#{idx}.interest_id = ?)", i]
  
        relation = relation.joins(join_clause)
      end
  </code></pre>