按照has_many关联的计数排序

时间:2012-10-18 09:45:44

标签: sql ruby-on-rails-3 sql-order-by activeadmin

我的模特是:

service_provider has_many问题, 问题belongs_to service_provider

在Activeadmin中,我想索引我的service_providers并按他们的questions_count对它们进行排序。

所以,为了得到一个字段,我可以排序,我定义我的default_scope像这样:

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

我的列定义如下:

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

索引我的服务提供商时,一切看起来都很好。但是当我按他们的questions_count说,我得到以下错误:

 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

所以,他尝试ORDER BY“service_providers”。“questions_count”desc。事实上,他应该ORDER BY“questions_count”desc。

有什么建议,我怎么能告诉他在订单声明中使用正确的字段名?

2 个答案:

答案 0 :(得分:1)

应该是

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

答案 1 :(得分:0)

.order("COUNT(service_provider_id)")

或者只是

.order("questions_count")