Skip to main content

Sorting

sort adds one option to the sort menu of an index page or dashboard. Call it once per sortable column.

Quick example​

cm_index do
sort column: "name", display_name: "Name"
sort column: "updated_at", display_name: "Updated At"
sort column: "created_at", display_name: "Created At", default: true, default_direction: "desc"

column :name
end

Options​

sort(column:, display_name: nil, default: false, default_direction: nil, datatype: nil, sort_with: nil, display_if: nil)
NameTypeDefaultDescription
columnStringrequiredColumn to sort by. <association>_<column> sorts by an associated table's column.
display_nameStringcolumn, titleizedLabel in the sort menu.
defaultBooleanfalseApply this sort when the user hasn't chosen one.
default_directionString"desc""asc" or "desc". Setting it also makes the sort a default.
datatypeString"STRING"Cast for JSONB values: STRING, INTEGER, NUMERIC, DATE or TIMESTAMP.
sort_withSymbolnilModel scope called with the direction ("asc" / "desc") instead of the default ordering.
display_ifProc->(_arg) { true }Lambda returning whether to offer this sort.

When no sort is marked as default, the first one is applied in descending order. Records are ordered with NULLS LAST.

sort_column and sort_direction are deprecated: use sort.

Recipes​

Sort by an associated model's column​

Name the column <association>_<column>. cm-admin joins the association and orders by that table's column, which works for belongs_to, has_one and has_many. Delegating with a prefix gives you a matching method to display:

app/models/user.rb
belongs_to :organisation
delegate :name, to: :organisation, prefix: true, allow_nil: true
sort column: "organisation_name", display_name: "Organisation"
column :organisation_name

Add a database index on the associated column if the list is large.

Sort by a JSONB attribute​

For a key declared with store_accessor, set the datatype of the stored value:

sort column: "verified_at", display_name: "Verified At", datatype: "TIMESTAMP"

Custom sort logic​

sort column: "request_due_date", display_name: "Request Due Date", sort_with: :sort_by_due_date_nulls_first
app/models/request.rb
scope :sort_by_due_date_nulls_first, ->(direction) {
order(Arel.sql("request_due_date #{direction} NULLS FIRST"))
}

Only offer a sort to some users​

sort column: "created_at", display_name: "Created At", display_if: ->(_obj) { Current.user.admin? }