Forum: Ruby on Rails Referencing associated records in a named scope

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Max W. (Guest)
on 2009-04-20 14:24
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
This topic is locked and can not be replied to.