has_many :through

Hello,

I have 4 tables Provinces, Districts, Cities and Municipalities.

A Province has many Districts. A district has many Cities, and a City has many Municipalities.

With this code :

class Province < ActiveRecord::Base

relationship

has_many :districts

has_many :cities, :through => :districts

end

I can do this :

@province = Province.find(:first)

@ province.cities.first.name

I would like to go one step further and be able to do

@province.districts.first.name

Is it possible?

How can I do that?

Thanks for sharing your experience.

Thomas.

Thomas Balthazar wrote:

Hello, I have 4 tables Provinces, Districts, Cities and Municipalities. A Province has many Districts. A district has many Cities, and a City has many Municipalities.

With this code :

class Province < ActiveRecord::Base   # relationship   has_many :districts   has_many :cities, :through => :districts end

I can do this : @province = Province.find(:first) @province.cities.first.name

I would like to go one step further and be able to do @province.districts.first.name

Is it possible? How can I do that?

Thanks for sharing your experience. Thomas.

Unless there's a typo in your code somewhere, I don't think there's any reason that you shouldn't be able to do that now, with what you've already got.

Oups!

What I would like to do is :

@province.municipalities.first.name

Thanks for pointing that out, Jon.

AR doesn't support nested has_many :through. You can try following :

class Province < ActiveRecord::Base   # relationship   has_many :districts   has_many :cities, :through => :districts, :include => :municipalities

  def municipalities      self.cities.map(&:municipalities)   end end

Please note that this could nuke your memory if you're dealing with large datasets.

Thanks for your answer!

Thomas.

Although it does with the has_many_through plugin [http:// code.torchbox.com/svn/rails/plugins/nested_has_many_through/] :slight_smile:

I wouldn't really suggest using that plugin if you're not on stable rails release.