title: Rails STI association with subclasses
body: <p>I'm getting some strange behaviour when fetching collections from a has_many association with rails 3 when using STI. I have:</p>
  
  <pre><code>class Branch &lt; ActiveRecord::Base
     has_many :employees, class_name: 'User::Employee'
     has_many :admins, class_name: 'User::BranchAdmin'
  end
  
  class User &lt; ActiveRecord::Base
  end
  
  class User::Employee &lt; User
    belongs_to :branch
  end
  
  class User::BranchAdmin &lt; User::Employee
  end
  </code></pre>
  
  <p>The desired behaviour is that <code>branch.employees</code> returns all employees including branch admins. The branch admins only seem to be 'loaded' under this collection when they have been accessed by <code>branch.admins</code>, this is output from the console:</p>
  
  <pre><code>Branch.first.employees.count
  =&gt; 2
  
  Branch.first.admins.count
  =&gt; 1
  
  Branch.first.employees.count
  =&gt; 3
  </code></pre>
  
  <p>This can be seen in the generated SQL, the first time:</p>
  
  <pre><code>SELECT COUNT(*) FROM "users" WHERE "users"."type" IN ('User::Employee') AND "users"."branch_id" = 1
  </code></pre>
  
  <p>and the second time:</p>
  
  <pre><code>SELECT COUNT(*) FROM "users" WHERE "users"."type" IN ('User::Employee', 'User::BranchAdmin') AND "users"."branch_id" = 1
  </code></pre>
  
  <p>I could solve this problem by just specifying: </p>
  
  <pre><code>class Branch &lt; ActiveRecord::Base
     has_many :employees, class_name: 'User'
     has_many :admins, class_name: 'User::BranchAdmin'
  end
  </code></pre>
  
  <p>since they all be found from their branch_id but this creates problems in the controller if I want to do <code>branch.employees.build</code> then the class will default to <code>User</code> and I have to hack at the type column somewhere. I have got around this for now with:</p>
  
  <pre><code>  has_many :employees, class_name: 'User::Employee', 
      finder_sql: Proc.new{
        %Q(SELECT users.* FROM users WHERE users.type IN          ('User::Employee','User::BranchAdmin') AND users.branch_id = #{id})
      },
      counter_sql: Proc.new{
        %Q(SELECT COUNT(*) FROM "users" WHERE "users"."type" IN ('User::Employee', 'User::BranchAdmin') AND "users"."branch_id" = #{id})
      }
  </code></pre>
  
  <p>but I would really like to avoid this if possible. Anyone, any ideas?</p>
  
  <p>EDIT:</p>
  
  <p>The finder_sql and counter_sql haven't really solved it for me because it seems that parent associations don't use this and so <code>organisation.employees</code> that <code>has_many :employees, through: :branches</code> will again only include the <code>User::Employee</code> class in the selection.</p>