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:

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

In this case I will get the error "undefined method `reservations’ for

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



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.


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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs