roman
roman

Reputation: 97

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?

Upvotes: 0

Views: 669

Answers (2)

Tan Nguyen
Tan Nguyen

Reputation: 3376

It should be

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

Upvotes: 1

Salil
Salil

Reputation: 47482

.order("COUNT(service_provider_id)")

OR Just

.order("questions_count")

Upvotes: 0

Related Questions