I frequently need to do something like the following (pseudo-code):
Company.find(:conditions => ["city == 'Sandusky']).employees
If i understood it well, you have two tables, Companies and employees, and you want to get all the employees from several companies given some conditions.
ActiveRecord makes it pretty-straight forward to get this.
Employee.find(:all, :include=>:company, :conditions=>"companies.city='Sandusky'")
If you want to get unique results, you could use uniq over the resulting array, but since we are using include, the array you are getting is including the companies too; with a bit of mapping, we can just filter that out.
Employee.find(:all, :include=>:company, :conditions=>"companies.city='Sandusky'").map{|e| e.attributes}.uniq
this way, you are converting the resulting array in an array with only the attributes of Employee model, and now you can just use uniq to remove any dupplicates.
Another approach in order to avoid the mapping would be not using :include, but :join and :select, with the only "problem" that you have to tell ActiveRecord how to join the tables and I would say is a bit less idiomatic because you are in some way breaking the ORM pattern. Also, if you are joining tables through a many to many relationship with another table in the middle, the join could get tricky, so I'd recommed to go with the :include/map solution.
regards,
javier
jramirez@aspgems.com