Merged
requested to merge github/fork/sinsoku/use_correct_values_when_sorting_by_has_many_associations into master
Created by: sinsoku
When sorting by has_many associations, Administrate assumes that the table and column names are #{attribute}.id
.
An error will occur if the user defines a different association than the table name or uses a primary key other than :id.
For example, the following code causes an error.
# db/migrate/20201016000000_create_users.rb
create_table :users, primary_key: "uid" do |t|
t.references :company
t.timestamps
end
# app/models/company.rb
class Company < ApplicationRecord
has_many :employee, class_name: "User"
end
Administrate::Order.new("employee", "asc").apply(Company.all).take
# Company Load (0.5ms) SELECT "companies".* FROM "companies" LEFT OUTER JOIN "users" ON "users"."company_id" = "companies"."id" GROUP BY "companies"."id" ORDER BY COUNT(employee.id) asc LIMIT ? [["LIMIT", 1]]
# Traceback (most recent call last):
# 1: from (irb):1
# ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: employee.id)
This commit fixes Administrate::Order
to use the correct table and column names.