Referencing associated records in a named scope


#1

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