Search code examples
ruby-on-railsruby-on-rails-5

Fetching data 3 levels deep


My aim is whether is it possible to fetch my required data the fastest way / with the least amount of queries to the database.


My Rails models are as follow:

AA has_many BB 
BB has_many CC
CC has_many DD

I would like to get all DD that has AA.name = "xxx"


I am stuck on the above on not knowing how to use joins to make sure I can get the DDs. Any help would be appreciated


Solution

  • Use joins passing the reference of each model:

    DD.joins(cc: { bb: :aa }).where(aas: { name: 'xxx' })
    

    As cc, bb, aa in a reverse order starting from dd have a belongs_to relationship between themselves, they're expressed in their single form.

    Also note that the .where(aas: { name: 'xxx' }), the aas is the plural for aa