# Name\_scope and has\_many associations

**URL:** <https://www.ruby-forum.com/t/name-scope-and-has-many-associations/144915>\
**Category:** Rails\
**Created:** [August 4, 2008, 11:13am UTC](https://www.ruby-forum.com/t/name-scope-and-has-many-associations/144915 "2008-08-04T11:13:08Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![liseki](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/7ab992/32.png) [@liseki](https://www.ruby-forum.com/u/liseki)\
**Post date:** [August 4, 2008, 11:13am UTC](https://www.ruby-forum.com/t/name-scope-and-has-many-associations/144915/1 "2008-08-04T11:13:08Z")

</div>

Hey people,

I’m using named\_scope in some associations and I’ve run into a bit of a  
problem. For a simple association between two tables, named\_scope works  
fine:

class Person \< AR:Base  
has\_many :cars  
end

class Car \< AR:Base  
belong\_to :person  
named\_scope :toyota, :conditions =\> {:make =\> ‘toyota’}  
end

peter.cars.toyota works as expected.

Now let’s say you have a more complex association. Say, a country has  
regions, a region has districts and a district has people.

class country \< AR:Base  
has\_many :regions  
has\_many :people, :finder\_sql =\>  
'SELECT p.\* ’ +  
'FROM people p, regions r, districts d ’ +  
'WHERE r.country\_id = #{id} AND d.region\_id = r.id AND ’ +  
‘p.district\_id = d.id’  
end  
class region \< AR:Base  
belongs\_to :country  
has\_many :districts  
end  
class district \< AR:Base  
belongs\_to :region  
has\_many :people  
end  
class person \< AR:Base  
belongs\_to :district  
named\_scope :high\_earners, :conditions =\> [“salary\_level \> 6”]  
end

antigua.people # all the people in all the districts and regions of  
Antigua

However antigua.people.high\_earners returns nil. Why is this?

Thanks for any ideas you throw my way.

---

<div class="post-metadata">

**Author:** ![liseki](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/7ab992/32.png) [@liseki](https://www.ruby-forum.com/u/liseki)\
**Post date:** [August 4, 2008, 12:19pm UTC](https://www.ruby-forum.com/t/name-scope-and-has-many-associations/144915/2 "2008-08-04T12:19:46Z")

</div>

Just realized the problem. For complex has\_many associations built  
using a custom finder sql, the find\_in\_collection method is not added!
