title: Rails 3 Finding and Grouping over multiple tables with at least one matching parameter
body: <p>I have a database of Users. Users have Skills and Interests which relate to the same Tags table. I need to create a search query that takes an array of Tags and finds all users with at least one of those tags as a Skill, ordered by largest number found.</p>
  
  <p>From the little bit of SQL I know, I'm thinking: </p>
  
  <ol>
  <li>join the users table with the skills (tags) table</li>
  <li>filter by tags that are within the provided array</li>
  <li>then group by user id</li>
  <li>add a having > 0 on the count</li>
  </ol>
  
  <p>and returning that result. The problem is I can't figure out how to do that with Rails.</p>
  
  <p>So if someone could say whether this is the correct method or not, and how to do so in Rails, I'd much appreciate it.</p>
  
  <pre><code>#User Model
  class User &lt; ActiveRecord::Base
      has_and_belongs_to_many :skills, :class_name =&gt; "Tag", :join_table =&gt; "skills_users"
      has_and_belongs_to_many :interests, :class_name =&gt; "Tag", :join_table =&gt; "interests_users"
  end
  
  #Tag Model
  class Tag &lt; ActiveRecord::Base
      has_and_belongs_to_many :skilled_users, :class_name =&gt; "User", :join_table =&gt; "skills_users"
      has_and_belongs_to_many :interested_users, :class_name =&gt; "User", :join_table =&gt; "interests_users"
  end
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>I did find this, which would work but I feel like its a hack around method for solving this. <a href="https://stackoverflow.com/questions/5176664/rails-finding-all-posts-with-certain-tags-without-using-acts-as-taggable">Rails finding all posts with certain tags without using acts_as_taggable</a></p>
  
  <p><strong>Update 2</strong></p>
  
  <pre><code>User.find(:all, :joins =&gt; :skills, :conditions =&gt; { :tags =&gt; { :id =&gt; [1,2,3] }})
  </code></pre>
  
  <p>I was able to get a list of all users who had any of the skills passed in. This mean duplicate rows. Unfortunately when I grouped by user id, they didn't group because the Tag information was attached to the row. I also haven't figure out how to count the tags.</p>