Skip to content

Commit

Permalink
Use the correct foreign key when sorting belongs_to associations (#1552)
Browse files Browse the repository at this point in the history
Don't assume the foreign key will be ${FOO}_id.

Fixes #1182.
  • Loading branch information
pablobm committed Feb 18, 2020
1 parent c15291e commit 990896c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
6 changes: 5 additions & 1 deletion lib/administrate/order.rb
Expand Up @@ -62,7 +62,7 @@ def order_by_count(relation)
end

def order_by_id(relation)
relation.reorder("#{attribute}_id #{direction}")
relation.reorder("#{foreign_key(relation)} #{direction}")
end

def has_many_attribute?(relation)
Expand All @@ -76,5 +76,9 @@ def belongs_to_attribute?(relation)
def reflect_association(relation)
relation.klass.reflect_on_association(attribute.to_s)
end

def foreign_key(relation)
reflect_association(relation).foreign_key
end
end
end
17 changes: 13 additions & 4 deletions spec/lib/administrate/order_spec.rb
Expand Up @@ -73,12 +73,15 @@
context "when relation has belongs_to association" do
it "orders by id" do
order = Administrate::Order.new(:name)
relation = relation_with_association(:belongs_to)
relation = relation_with_association(
:belongs_to,
foreign_key: "some_foreign_key",
)
allow(relation).to receive(:reorder).and_return(relation)

ordered = order.apply(relation)

expect(relation).to have_received(:reorder).with("name_id asc")
expect(relation).to have_received(:reorder).with("some_foreign_key asc")
expect(ordered).to eq(relation)
end
end
Expand Down Expand Up @@ -176,9 +179,15 @@ def relation_with_column(column)
)
end

def relation_with_association(association)
def relation_with_association(association, foreign_key: "#{association}_id")
double(
klass: double(reflect_on_association: double(macro: association)),
klass: double(
reflect_on_association: double(
"#{association}_reflection",
macro: association,
foreign_key: foreign_key,
),
),
)
end
end

0 comments on commit 990896c

Please sign in to comment.