title: Filtering child objects in a has_many :through relationship in Rails 3
body: <p>Greetings,</p>
  
  <p>I have an application where <code>Companies</code> and <code>Users</code> need to belong to each other through a <code>CompanyMembership</code> model, which contains extra information about the membership (specifically, whether or not the User is an admin of the company, via a boolean value <code>admin</code>). A simple version of the code:</p>
  
  <pre><code>class CompanyMembership &lt; ActiveRecord::Base
    belongs_to :company
    belongs_to :user
  end
  
  class Company &lt; ActiveRecord::Base
    has_many :company_memberships
    has_many :users, :through =&gt; :company_memberships
  end
  
  class User &lt; ActiveRecord::Base
    has_many :company_memberships
    has_many :companies, :through =&gt; :company_memberships
  end
  </code></pre>
  
  <p>Of course, this makes it simple to get all the members of a company via <code>company.users.all</code>, et al. However, I am trying to get a list of all Users in a Company who are admins of that Company (and also to test whether a user is an admin of a given company). My first solution was the following in <code>company.rb</code>:</p>
  
  <pre><code>def admins
    company_memberships.where(:admin =&gt; true).collect do |membership|
      membership.user
    end
  end
  
  def is_admin?(user)
      admins.include? user
  end
  </code></pre>
  
  <p>While this works, something feels inefficient about it (it's iterating over each membership, executing SQL each time, right? Or is Relation smarter than that?), and I'm not sure if there's a better way to go about this (perhaps using scopes or the fancy new <code>Relation</code> objects that Rails 3 uses?).</p>
  
  <p>Any advice on the best way to procede (preferably using Rails 3 best practices) would be greatly appreciated!</p>