简体   繁体   中英

Order by count of a has_many association

My models are:

service_provider has_many questions, question belongs_to service_provider

In Activeadmin, i want to index my service_providers and sort them by their questions_count.

So, to get a field, i can sort by, i define my default_scope like this:

scope "all", :default => true do |sp|
  sp.joins("LEFT JOIN questions on questions.service_provider_id = service_providers.id")
    .select("service_providers.*, COUNT(service_provider_id) as questions_count")
    .group("service_providers.id")
end

and my column definitions looks like:

column :questions, :sortable => "questions_count" do |sp|
  sp.questions_count
end

When indexing my serviceproviders, everything looks fine. But when i oder by their questions_count, i get the following error:

 SQLite3::SQLException: no such column: service_providers.questions_count: SELECT  service_providers.*, COUNT(service_provider_id) as questions_count FROM "service_providers" LEFT JOIN questions on questions.service_provider_id = service_providers.id GROUP BY service_providers.id ORDER BY "service_providers"."questions_count" desc LIMIT 30 OFFSET 0

So, he tries to ORDER BY "service_providers"."questions_count" desc. Infact, he should ORDER BY "questions_count" desc.

Any suggestions, how i can tell him to use the right fieldname in his order-statement?

它应该是

ServiceProvider.joins(:questions).group("service_providers.id").order("count(service_providers.id) DESC")
.order("COUNT(service_provider_id)")

要不就

.order("questions_count")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM