Skip to main content

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 joins and order clauses.
  • The column name (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_name or cm_role_name is not indexed or heavily queried, consider adding proper database indexes.