📚 Sorting by Delegated Attributes in CM Admin
CM Admin supports sorting on delegated or associated model attributes by specifying them in the sortable_columns configuration. 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
sortable_columns [
  { column: 'created_at', display_name: 'Created At', default: true, default_direction: 'desc' },
  { column: 'updated_at', display_name: 'Updated At' },
  { column: 'first_name', display_name: 'Name' },
  { column: 'organisation_name', display_name: 'Organisation' },
  { 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.