diff --git a/lib/administrate/order.rb b/lib/administrate/order.rb index 30789dc0ea..dea112a1eb 100644 --- a/lib/administrate/order.rb +++ b/lib/administrate/order.rb @@ -59,10 +59,12 @@ def order_by_association(relation) end def order_by_count(relation) + klass = reflect_association(relation).klass + query = "COUNT(#{klass.table_name}.#{klass.primary_key}) #{direction}" relation. left_joins(attribute.to_sym). group(:id). - reorder(Arel.sql("COUNT(#{attribute}.id) #{direction}")) + reorder(Arel.sql(query)) end def order_by_id(relation) diff --git a/spec/lib/administrate/order_spec.rb b/spec/lib/administrate/order_spec.rb index 7899926ef9..9cf2eed3f0 100644 --- a/spec/lib/administrate/order_spec.rb +++ b/spec/lib/administrate/order_spec.rb @@ -67,7 +67,10 @@ context "when relation has_many association" do it "orders the column by count" do order = Administrate::Order.new(:name) - relation = relation_with_association(:has_many) + relation = relation_with_association( + :has_many, + klass: double(table_name: "users", primary_key: "uid"), + ) allow(relation).to receive(:reorder).and_return(relation) allow(relation).to receive(:left_joins).and_return(relation) allow(relation).to receive(:group).and_return(relation) @@ -76,7 +79,7 @@ expect(relation).to have_received(:left_joins).with(:name) expect(relation).to have_received(:group).with(:id) - expect(relation).to have_received(:reorder).with("COUNT(name.id) asc") + expect(relation).to have_received(:reorder).with("COUNT(users.uid) asc") expect(ordered).to eq(relation) end end @@ -190,13 +193,18 @@ def relation_with_column(column) ) end - def relation_with_association(association, foreign_key: "#{association}_id") + def relation_with_association( + association, + foreign_key: "#{association}_id", + klass: nil + ) double( klass: double( reflect_on_association: double( "#{association}_reflection", macro: association, foreign_key: foreign_key, + klass: klass, ), ), )