Forum: Ruby on Rails nested has_many associations

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.
1e64a49d9a544dd3c07c9cf25cb9428d?d=identicon&s=25 Chris (Guest)
on 2006-02-03 22:23
(Received via mailing list)
My question is whether the rails helper methods for handling
associations can
be nested (see examples below). I suspect not as currently I'm
getting "unknown method" if I try and use two associations in one call.

The essence of the code is

class User << ActiveRecord::Base
  has_many :items

class Items << ActiveRecord::Base
  has_many :reservations
  belongs_to :user

class Reservations << ActiveRecord::Base
  belongs_to :item

I've specified foreign_key fields etc.

What works:
  user.items.size
  item.reservations.size

What doesn't work (and my question for the group)
  user.items.reservations.size
In other words returning the number of reservations made against all
items
that are owned by a user.

In this case I will get the error "undefined method `reservations' for
Item:Class

Is this supposed to work? If not how should I work around it?

thanks

Chris
41165a7e7126d616a0ae0762e00718e2?d=identicon&s=25 BigSmoke (Guest)
on 2006-02-04 17:32
(Received via mailing list)
The pluralization of your class names doesn't exectly make it easier
for me to understand your code, but here goes.

If User has_many :items, user.items will return a list. You have to
select any "Items" object from this list for which you can then
request the reservations.

user.items[0].reservations

I don't suppose your example would work anyway because you leave it up
to AR to guess the class names for your associations while the class
names don't follow the pluralization rules.

Hoping this will help you,

  - Rowan Rodrik
This topic is locked and can not be replied to.