How to find Entity and Daughters in a single sql

0

I have 3 classes that relate as follows:

class AnamnesisModel < ApplicationRecord
  has_many :anamnesis_questions
  accepts_nested_attributes_for :anamnesis_questions
end

class AnamnesisQuestion < ApplicationRecord
  belongs_to :anamnesis_model
  belongs_to :question
end

class Question < ApplicationRecord
end

The point is that when selecting a particular Anamnesis Template, I would like load the 3 in a single sql , as I am using rails as webAPI I want to send that all filled object up.

So far I've been able to do something pretty good this way.

render json: @anamnesis_model.to_json(:include => {:anamnesis_questions => {:include => :question}})

The problem with this solution is that it does not do everything in one sql.

(Example of an anamnesis with 3 questions)

    Started GET "/anamnesis_models/41" for ::1 at 2017-07-12 15:03:50 -0300
Processing by AnamnesisModelsController#show as HTML
  Parameters: {"id"=>"41"}
  AnamnesisModel Load (2.0ms)  SELECT  "anamnesis_models".* FROM "anamnesis_models" WHERE "anamnesis_models"."id" = ? LIMIT ?  [["id", 41], ["LIMIT", 1]]
  AnamnesisQuestion Load (1.0ms)  SELECT "anamnesis_questions".* FROM "anamnesis_questions" WHERE "anamnesis_questions"."anamnesis_model_id" = ?  [["anamnesis_model_id", 41]]
  Question Load (1.0ms)  SELECT  "questions".* FROM "questions" WHERE "questions"."id" = ? LIMIT ?  [["id", 61], ["LIMIT", 1]]
  Question Load (1.0ms)  SELECT  "questions".* FROM "questions" WHERE "questions"."id" = ? LIMIT ?  [["id", 62], ["LIMIT", 1]]
  Question Load (3.0ms)  SELECT  "questions".* FROM "questions" WHERE "questions"."id" = ? LIMIT ?  [["id", 63], ["LIMIT", 1]]
    
asked by anonymous 12.07.2017 / 20:20

1 answer

0

I recommend reading the site below. link

Within the reading of the content I tested in specific with the use of a

  

LEFT OUTER JOIN

To run with a single query, I used

eager_load

Good luck.

    
28.09.2017 / 23:26