AssociatedSort
đ Sorting by Delegated Attributes in CM Adminâ
CM Admin supports sorting on delegated or associated model attributes by adding them with the sort DSL method. This is particularly useful when you want to sort based on related models, such as organisation.name or cm_role.name.
â Prerequisitesâ
Ensure that:
- The associated attributes are properly delegated in the model.
- Your database joins can support sorting on the associated table columns.
đ Example Setupâ
Given a model like:
# app/models/user.rb
class User < ApplicationRecord
belongs_to :organisation
belongs_to :cm_role
delegate :name, to: :organisation, prefix: true, allow_nil: true
delegate :name, to: :cm_role, prefix: true, allow_nil: true
end
In your CM Admin File:
# app/models/cm_admin/user.rb
sort column: 'created_at', display_name: 'Created At', default: true, default_direction: 'desc'
sort column: 'updated_at', display_name: 'Updated At'
sort column: 'first_name', display_name: 'Name'
sort column: 'organisation_name', display_name: 'Organisation'
sort column: 'cm_role_name', display_name: 'Role'
đ§ Behind the Scenesâ
To support sorting via associations:
- CM Admin uses Arel or ActiveRecord
joinsandorderclauses. - The
columnname (e.g.,organisation_name) should match a delegated method or virtual attribute on the model.
â ïž Notesâ
- If you encounter SQL errors when sorting on these columns, you may need to explicitly define the join logic in your CM Admin controller or scope.
- If
organisation_nameorcm_role_nameis not indexed or heavily queried, consider adding proper database indexes.