user9276715
user9276715

Reputation:

Get all has_many instances for each collection item

I have the models of:

Task which has_many :comments and has_many :checklists

Comment which has_many :activities

Checklist which has_many :activities

-> (polymorphic association).

I want to get every Activity there is in a Task, for example, if I do something like:

Task.first.checklists.first.activities

it returns result, so does:

Task.first.comments.first.activities` 

but I can not manage to write proper syntax that gets me every activity there is in a Task, thank you in advance.

Upvotes: 0

Views: 39

Answers (1)

potashin
potashin

Reputation: 44611

You can define has_many through: associations:

class Task 
  has_many :comments
  has_many :checklists

  has_many :comment_activities, through: :comments, source: :activities
  has_many :checklist_activities, through: :checklists, source: :activities
end

and use them as follows:

Task.first.checklist_activities
Task.first.comment_activities

Upvotes: 1

Related Questions