Linked associations question please help

I have a Users model. Users ‘have many’ Stories, and Stories have
many Items.

This structure allows the sharing of Items between Stories and Stories
between Users.

But given there is no direct ‘ownership’ link between Users and Items,
what is the best way of building a list of Items which belong to a
Story to which a given User has access.

something like:


obviously doesn’t work.

I’ve written some nested blocks ie:

users.each do |user| |story| |item|

which works but is ugly and slow.

I could keep an index table of items linked to users but this is
redundant for most of my application. I’m sure there is a more
obvious, simple way of doing this but I haven’t come across it.

Any help gratefully received.


You have to look at 'nested has_many associations'. Search it here


And By applying this in above case you can directly say




Have you anywhere specified the HABTM relation?It not supported I
think. Please check your relations like

user has_many stories
user has_many items through stories

belongs_to user
has_many items

belongs_to story


Users have many stories through userstorylinks…

has_many :userstorylinks
has_many :stories, :through=>:userstorylinks

Stories are even more associated…

has_many :userstorylinks, :dependent=>:destroy
has_many :users, :through=>:userstorylinks
has_many :storyitemlinks
has_many :items, :through=>:storyitemlinks
has_many :storycontactlinks
has_many :contacts, :through=>:storycontactlinks
has_many :storycompanylinks
has_many :companies, :through=>:storycompanylinks

Does this screw up your suggestion?

On Oct 19, 10:58 am, Sijo k g [email protected]

Thanks so much for the quick response.

Yes that makes sense, and I wasn’t aware it was possible. However
having added to my User model:

has_many :items, :through=>:stories

I am getting the following error when trying to call @user.items

ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid
source reflection macro :has_many :through for
has_many :items, :through => :stories. Use :source to specify the
source reflection.

I have to admit Reflections are something beyond my knowledge, and I
noted suggestions that nested HABTM associations weren’t supported in
earlier versions of Rails.

Any thoughts?