Rails 按 has

编程入门 行业动态 更新时间:2024-10-28 17:24:57
本文介绍了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

本文发布于:2023-10-17 11:16:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500733.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!