Nested has_many associations

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

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