ruby-on-railsactiverecordactive-relation

Rails ActiveRelation Sub Relation


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


Solution

  • 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.