diff --git a/app/controllers/administrate/application_controller.rb b/app/controllers/administrate/application_controller.rb index dad67482ae9cd8e4bfcc948b8589d8b86c59db60..7e9d63034873f33dbe140b7fce49114cdbcc9306 100644 --- a/app/controllers/administrate/application_controller.rb +++ b/app/controllers/administrate/application_controller.rb @@ -101,10 +101,24 @@ module Administrate end def order - @order ||= Administrate::Order.new( - params.fetch(resource_name, {}).fetch(:order, nil), - params.fetch(resource_name, {}).fetch(:direction, nil), - ) + attribute = params.fetch(resource_name, {}).fetch(:order, nil) + direction = params.fetch(resource_name, {}).fetch(:direction, nil) + field = order_by_field(dashboard_attribute(attribute)) + @order ||= Administrate::Order.new(attribute, direction, field) + end + + def order_by_field(dashboard_attribute) + return unless class_inherited_belongs_to?(dashboard_attribute) + dashboard_attribute.options[:order] + end + + def class_inherited_belongs_to?(dashboard_attribute) + return false unless dashboard_attribute.try(:deferred_class) + dashboard_attribute.deferred_class <= Administrate::Field::BelongsTo + end + + def dashboard_attribute(attribute) + dashboard.attribute_types[attribute.to_sym] if attribute end def dashboard diff --git a/lib/administrate/order.rb b/lib/administrate/order.rb index 5989902c8fce05105f9ce27ad316f509b69c5e4f..15d9a1ed9cff597498c65f448705571e26357612 100644 --- a/lib/administrate/order.rb +++ b/lib/administrate/order.rb @@ -1,8 +1,9 @@ module Administrate class Order - def initialize(attribute = nil, direction = nil) + def initialize(attribute = nil, direction = nil, field = nil) @attribute = attribute @direction = direction || :asc + @field = field end def apply(relation) @@ -32,7 +33,7 @@ module Administrate private - attr_reader :attribute + attr_reader :attribute, :field def reversed_direction_param_for(attr) if ordered_by?(attr) @@ -49,7 +50,9 @@ module Administrate def order_by_association(relation) return order_by_count(relation) if has_many_attribute?(relation) - return order_by_id(relation) if belongs_to_attribute?(relation) + if belongs_to_attribute?(relation) + return field ? order_by_attribute(relation) : order_by_id(relation) + end relation end @@ -65,6 +68,12 @@ module Administrate relation.reorder("#{attribute}_id #{direction}") end + def order_by_attribute(relation) + relation. + joins(attribute.to_sym). + reorder("#{attribute.pluralize}.#{field} #{direction}") + end + def has_many_attribute?(relation) reflect_association(relation).macro == :has_many end