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:

current_user.stories.items

obviously doesn’t work.

I’ve written some nested blocks ie:

users.each do |user|
user.stories.each.do |story|
story.items.each.do |item|
end
end
end

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.

Hi

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

http://guides.rubyonrails.org/association_basics.html

Sijo

And By applying this in above case you can directly say

current_user.items

Sijo

Hi

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

user.rb
user has_many stories
user has_many items through stories

story.rb
belongs_to user
has_many items

item.rb
belongs_to story

Sijo

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?

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