# Referencing associated records in a named scope

**URL:** <https://www.ruby-forum.com/t/referencing-associated-records-in-a-named-scope/165965>\
**Category:** Rails\
**Created:** [April 20, 2009, 12:24pm UTC](https://www.ruby-forum.com/t/referencing-associated-records-in-a-named-scope/165965 "2009-04-20T12:24:47Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [April 20, 2009, 12:24pm UTC](https://www.ruby-forum.com/t/referencing-associated-records-in-a-named-scope/165965/1 "2009-04-20T12:24:47Z")

</div>

Hi all

I have a situation like this:

class Country  
has\_many :policy\_indicator\_ratings  
has\_many :policy\_indicators, :through =\> :policy\_indicator\_ratings

class PolicyIndicatorRating  
belongs\_to :country  
belongs\_to :policy\_indicator

class PolicyIndicator  
has\_many :policy\_indicator\_ratings  
named\_scope :water, :conditions =\> [“sector = ?”, ‘water’]  
named\_scope :sanitation, :conditions =\> [“sector = ?”,‘sanitation’]

Now, i want to say something like

@country.policy\_indicators.water.each do |indicator|  
#do something with this country’s rating for this indicator  
end

It feels like i’m now forced to do something like this inside the loop:

rating =  
PolicyIndicatorRating.find\_by\_country\_id\_and\_policy\_indicator\_id(@country.id,  
indicator.id)

This seems clumsy - i’ve gone through the join model to get the  
indicator, and now i have to manually pull the join record out again.

Is there a way to set up the named scope on the join model, something  
like this?

#this won’t work but gets the idea across  
named\_scope :water, :conditions =\> (self.policy\_indicator.sector ==  
“water”)

??

Or, is there a nicer way to organise my schema to seperate out water  
indicators from sanitation indicators?

Grateful for any advice.  
thanks  
max
