How do eager_load with nesting controllers?

Asked

Viewed 24 times

0

In the index method of the controller Disputes::ConferencesController list all the conferences of disputes. The URL address is disputes/1/conferences.

My route schema is like this:

resources :disputes do
  scope module: :disputes do
    resources :conferences, shallow: true
  end
end

Unfortunately to get the conferences I need to do 2 queries in the database:

Dispute Load (0.3ms)  SELECT  "disputes".* FROM "disputes" WHERE "disputes"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
Conference Load (0.4ms)  SELECT "conferences".* FROM "conferences" WHERE "conferences"."dispute_id" = $1 ORDER BY "conferences"."scheduled_at" DESC  [["dispute_id", 1]]

The method index is that way:

def set_dispute
  @dispute = Dispute.find params[:dispute_id]
end

def index
  @conferences = @dispute.conferences.order(scheduled_at: :desc)

  render json: @conferences, each_serializer: ConferencesSerializer
end

How to get around this for only 1 query?

1 answer

0


Solution below solves this question. Just set to the method index a query that searches all conferences through the dispute_id, see below how it looks:

def set_conferences
  @conferences = Conference.where(dispute_id: params[:dispute_id])
                           .order scheduled_at: :desc
end

def index
  render json: @conferences, each_serializer: ConferencesSerializer
end

Don’t forget to add calls to before_action:

before_action :set_dispute, only: :create
before_action :set_conferences, only: :index

I hope to help some people.

Browser other questions tagged

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