thoughtbot/administrate

Field::HasMany loading too many records in Edit view

LandonSchropp opened this issue · 5 comments

I'm building a dashboard for my Price model. One of the attributes on this model is a HasMany field.

class Monetization::PriceDashboard < Administrate::BaseDashboard
  ...

  ATTRIBUTE_TYPES = {
    ...
    companies: Field::HasMany,
  }.freeze

  FORM_ATTRIBUTES = %i[
    ...
    companies
  ].freeze
end

This works fine locally, but in production, the input for the companies loads every record in the database. This is too much data, and the page crashes before it can finish rendering.

Is it possible to configure Field::HasMany to display a limited subset of the records for the edit drop-down? I'd expect the field to re-fetch the data when the user types in a more specific query.

Nitr commented

take a look at this

another solution is to define a scope in your model with limit: check tihs

I saw that, but I'm not sure if it solves my problem.

In our app, it really is possible to pick from any of the options—it's just the UI that's loading too many of them at once to pick from. If I were to limit them, then I'd exclude valid options to choose from.

An ideal solution for our use case would be a dropdown that lazy-loads its contents with a dashboard method that's capable of selecting a subset of our models based on a query string.

Nitr commented

I saw that, but I'm not sure if it solves my problem.

In our app, it really is possible to pick from any of the options—it's just the UI that's loading too many of them at once to pick from. If I were to limit them, then I'd exclude valid options to choose from.

An ideal solution for our use case would be a dropdown that lazy-loads its contents with a dashboard method that's capable of selecting a subset of our models based on a query string.

In my experience,

  1. I created controller named SuggestionsController with only index action. Something like this...
  class SuggestionsController < ActionController::API
    def index
      resources = authorized_scope(params[:resource_class].constantize.all).search(params.require(:q))
      @page, @resources = pagy(resources)
    end
  end
  1. Then I had to override _form.html.erb partials for belongs_to, has_one.... for all associative fields in such a way all could work with select2-ajax-remote-data