本文介绍了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
发布评论