Skip to content
Jakob Skjerning edited this page Dec 4, 2017 · 3 revisions

We use https://github.com/thoughtbot/administrate as the admin-UI for most our apps. This is a collection of common customisation we've made.

Add a default sort order to dashboard

You want to order resources on the dashboard index by some field by default, yet leave it up to the user to change the sort order by clicking column headers.

module Admin
  class SomeController < Admin::ApplicationController
    private

    def default_order
      Administrate::Order.new(:created_at, :desc)
    end

    def order
      @_order ||= if params[:order] && params[:direction]
        order_from_params
      else
        default_order
      end
    end

    def order_from_params
      Administrate::Order.new(params[:order], params[:direction])
    end
  end
end

Sort an association dropdown

If you want to ensure the contents of the dropdown in a Field::BelongsTo or Field::HasMany is in a consistent order without adding a default_scope, you need to generate a custom field:

rails g administrate:field City

Customize CityField as a subclass of Administrate::Field::BelongsTo:

class CityField < Administrate::Field::BelongsTo
  ...
  private

  def candidate_resources
    super.order(:name)
  end
  ...
end

Update app/views/fields/city_field/_form.html.erb to render a collection instead of a text field by copying the contents of fields/belongs_to/_form.html.erb from Administrate (or modify by hand).