How to do eager_load with nested controllers?

0

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

My route plan looks 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 index method looks like this:

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 work around this for only 1 query?

    
asked by anonymous 28.12.2016 / 14:04

1 answer

0

The solution below addresses this issue. Just define for the method index a query that searches all conferences through dispute_id , see below how it is:

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

Do not 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.

    
28.12.2016 / 14:20