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)
| Name | Type | Default | Description |
|---|---|---|---|
column | String | required | Column to sort by. <association>_<column> sorts by an associated table's column. |
display_name | String | column, titleized | Label in the sort menu. |
default | Boolean | false | Apply this sort when the user hasn't chosen one. |
default_direction | String | "desc" | "asc" or "desc". Setting it also makes the sort a default. |
datatype | String | "STRING" | Cast for JSONB values: STRING, INTEGER, NUMERIC, DATE or TIMESTAMP. |
sort_with | Symbol | nil | Model scope called with the direction ("asc" / "desc") instead of the default ordering. |
display_if | Proc | ->(_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? }
Relatedβ
- Filters
- Saved views: users save their sort per view