Multiple layers of has_many :through

Either this is not supported or I'm just not seeing the forest for the trees. Here's the model relationship I currently have that works:

class Officer < AR::Base

has_many :officer_relationships

  has_many :clients, :through => :officer_relationships end

class Clients < AR::Base

has_many :officer_relationships

  has_many :officers, :through => :officer_relationships   has_many :accounts end

class OfficerRelationships < AR::Base   belongs_to :client   belongs_to :officer end

My problem is that I'm trying to associate the Account's model through the OfficerRelationship model and the Client model by doing the following:

class Officer < AR::Base

has_many :officer_relationships

  has_many :clients, :through => :officer_relationships   has_many :accounts, :through => :clients end

or the following:

class Officer < AR::Base

has_many :officer_relationships

  has_many :clients, :through => :officer_relationships   has_many :accounts, :through => :clients end

class OfficerRelationships < AR::Base   belongs_to :client   belongs_to :officer   has_many :accounts, :through => :client end

None of these work. Am I just trying to get more out of HasManyThrough than it was designed to? If so, can someone point me in the right direction as to the best DRY way to do this without replicating the OfficerRelationship model for every one of the client's accounts?

The has_many :xs :through => :ys also needs to have the has_many :ys

You want: officer = Officer.find(1)

officer.clients #=> to be all the clients officer.accounts #=> to be all the accounts

If the double-layer of has_many :through isn't working for you, you could always get officer.accounts by adding:

class Officer < ActiveRecord::Base    def accounts      self.clients.map(&:accounts).flatten    end end

You end up with a normal Array rather than an association proxy of the accounts, but perhaps this is enough for you needs, yes?

-Rob

Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com