How to search for Entity and Daughters in a single sql

Asked

Viewed 50 times

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 Model, I would like you to load all 3 into a single sql, as I am using Rails like webAPI I want to send this whole filled object up.

So far I’ve managed to do something almost good that way.

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

The problem with this solution is that it doesn’t 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]]
  • I got it here using joins + includes.

1 answer

0

  • OK,, I’ll take a look

Browser other questions tagged

You are not signed in. Login or sign up in order to post.