按has_many关联的结果计数进行Rails排序 [英] Rails order by results count of has_many association
本文介绍了按has_many关联的结果计数进行Rails排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无论如何,我是否可以根据孩子返回的项目数来订购结果( ASC
/ DESC
)模型(职位
)?
Is there anyway I can order the results (ASC
/DESC
) by number of items returned from the child model (Jobs
)?
@featured_companies = Company.joins(:jobs).group(Job.arel_table[:company_id]).order(Job.arel_table[:company_id].count).limit(10)
例如:我需要在顶部打印最高职位的公司
For example: I need to print the Companies with highest jobs on top
推荐答案
如果您希望经常使用此查询,建议您使用内置的 counter_cache
If you expect to use this query frequently, I suggest you to use built-in counter_cache
# Job Model
class Job < ActiveRecord::Base
belongs_to :company, counter_cache: true
# ...
end
# add a migration
add_column :company, :jobs_count, :integer, default: 0
# Company model
class Company < ActiveRecord::Base
scope :featured, order('jobs_count DESC')
# ...
end
然后像这样使用它
@featured_company = Company.featured
这篇关于按has_many关联的结果计数进行Rails排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文