How do I get all the children of an object's child objects?

Sorry for the confusing title, I wasn't sure how to say it. But I have a class User

that has a lot projects

. And the class Project

has a lot wbs_items

. So how do I get all wbs_items

that belongs to all projects

belonging to the same user?

Ideally I would do:

current_user.projects.wbs_items

      

But that won't work.

+3


source to share


3 answers


I managed to solve this problem by adding this line to my model:

has_many :wbs_items, :through => :projects

      



Then I could get everything wbs_items

by doing:

current_user.wbs_items

      

+4


source


# User model
has_many :projects
has_many :wbs_items, through: :projects

# this will return all wbs_items of the current user
current_user.wbs_items

      



+1


source


Without seeing my code, I would have thought that your approach might look like this:

  • Create a hash for the project / wbs_items relationship: Projects => [array_of_wbs_items]
  • Iterating over users and assigning wbs_items based on project search in project / wbs_items hash
0


source







All Articles