Rails 按 has_many 关联的结果计数排序 [英] Rails order by results count of has_many association
本文介绍了Rails 按 has_many 关联的结果计数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无论如何我可以通过从子模型(Jobs
)返回的项目数对结果(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
这篇关于Rails 按 has_many 关联的结果计数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文