Nick Vanderbilt
Nick Vanderbilt

Reputation: 38540

nested has_many

I am using Rails 2.3.5.

Class User < ActiveRecord::Base
  has_many :phones
end

class Phone < ActiveRecord::Base
  has_many :frequency_bands
end

I want to get all the frequency_bands for a user. I know I can write a method def freq_bands for User but I would like to know if it is possible to have has_many freq_bands for a User. In this way I can chain the call.

What I would like to have is

class User < ActiveRecor::Base
   has_many :frequence_bands, :through => phones
end

I think it is possible to have nested has_many using this plugin http://github.com/ianwhite/nested_has_many_through

However if possible I would like to avoid using another plugin and rely solely on rails.

Upvotes: 3

Views: 476

Answers (2)

sepp2k
sepp2k

Reputation: 370425

class User < ActiveRecord::Base
  has_many :phones
  has_many :frequence_bands, :through => :phones
end

Works just fine. You'd only need the nested has_many_through plugin if phones itself was also a has_many_through relationship, which it isn't in your example.

(Editor: And don't forget the ":" in front of the last attribute)

Upvotes: 7

cluesque
cluesque

Reputation: 1160

For rails 3, use the nested_has_many_through gem, for 3.1 this is rumored to work natively. (Haven't been able to try myself.)

Upvotes: 0

Related Questions