Has_many :through aggregation

Hello there,

I’m trying to figure out a way to use the has_many :through option to
aggregate collections in a specific way. Here’s an example of the
issue I’m trying to address:

create_table :companies do |t|
t.integer :parent_id


create_table :employees do |t|
t.integer :company_id

class Employee < ActiveRecord::Base
belongs_to :company

class Company < ActiveRecord::Base
has_many :companies, :class_name => ‘Company’, :foreign_key =>
has_many :employees
has_many :all_employees, :through => :children_companies, :source
=> :employees

A company may own other companies (has_many :companies). Each company
has its own set of employees (has_many :employees). What I’d like to
be able to do is have a search-able collection of all employees for a
company (including all the employees at each child company). However,
has_many :all_employees only gives me the employees of the child
companies, but not the companies proper employees.

If I use the :finder_sql option I lose finder_in_collection on the
association which is what I’m really after.

Any advice would be immensely appreciated.


You could grab both employees collection for the current company and
all the employees collections for all of the children companies the
“has_many :all_employees” and aggregate the results (I guess removing
duplicate entries if someone worked for both companies).

On Mar 18, 2:41 pm, “[email protected][email protected]

Not sure what you mean by ‘aggregate the results’? Adding the two
collections together with ‘+’ returns an array that does not respond
to find(:all, :conditions => …).


On Mar 18, 4:04 pm, “[email protected]” <ESPN3.DL-