Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use correct values when sorting by has_many associations #1800

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/administrate/order.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 11 additions & 3 deletions spec/lib/administrate/order_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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,
),
),
)
Expand Down