0

Im new to rails and have a question about accessing relations of relations in ActiveRecord.

Consider this psuedo code:

class Organisation
has_many: :projects

class Project
has_many: :tests

class Test
belongs_to: project

Effectively 3 levels. I need to access the Tests for a particular Organisation, although I can only go as deep as the Projects.

ie

@organisation = Organisation.find(params[:id], :include => [:projects])

Really, what I need to do would be something like

@organisation.projects.scripts.all

but from what im reading, thats not possible. So, whats the solution for this?

Thanks guys

divibisan
  • 11,659
  • 11
  • 40
  • 58
Cheyne
  • 1,964
  • 4
  • 27
  • 43

1 Answers1

1

You want something like this:

@organisation = Organization.includes(:projects => :tests).find(params[:id])
@organization.projects.collect(&:tests)

That will eagerly load one organization and all its projects and tests, and then it'll collect all tests for all projects related to that organization.

Veraticus
  • 15,944
  • 3
  • 41
  • 45