Snubber
Snubber

Reputation: 1024

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

Sorry for the confusing title, I wasn't sure how to word that. But I have the User class which has many projects. And the Project class has many wbs_items. So how do I get all the wbs_items that belong to all the projectsthat belong to a single user?

Ideally I would do:

current_user.projects.wbs_items

But this doesn't work.

Upvotes: 3

Views: 89

Answers (3)

grenierm5
grenierm5

Reputation: 186

Without seeing your code, I would think your approach could look like the following:

  1. Create hash for project/wbs_items relations: Projects => [array_of_wbs_items]
  2. Iterate over Users and assign wbs_items based on looking up the Project in the project/wbs_items hash

Upvotes: 0

kjmagic13
kjmagic13

Reputation: 1318

# 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

Upvotes: 1

Snubber
Snubber

Reputation: 1024

I was able to solve this by adding this line to my model:

has_many :wbs_items, :through => :projects

Then I could get all the wbs_items by doing:

current_user.wbs_items

Upvotes: 4

Related Questions