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]]