按has

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

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

发布评论

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

>www.elefans.com

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