Rails的查询排序基于嵌套模型的数量? [英] Rails query that sorts based on the count of a nested model?
本文介绍了Rails的查询排序基于嵌套模型的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个型号:组放大器; GroupMember
I have two models: Group & GroupMember
我想回组,排序最高的GroupMember算?您如何设置这种类型的连接/查询计数的Rails?
I would like to return Groups, sorted by the highest GroupMember Count? How do you setup this type of join/query count in Rails?
推荐答案
生命是如此容易得多与counter_cache:
Life is so much easier with counter_cache:
$ rails g migration add_group_member_counts_to_groups
# migration
def change
add_column :groups, :group_members_count, :integer, default: 0
end
class GroupMember < ActiveRecord::Base
belongs_to :group, counter_cache: true
end
class Group < ActiveRecord::Base
has_many :group_members
scope :order_by_group_members_count, order('group_members_count DESC')
end
Group.order_by_group_members_count # => What you're looking for
只有一个查询,只对团体表。
Only one query, only on the groups table.
修改
如果您需要重置group_members_count:
If you need to reset the group_members_count:
ids = Group.select(:id).map &:id
ids.each do |id|
Group.reset_counters(id, :group_members)
end
(因为reset_counters并不需要一组ID)
(because reset_counters doesn't take an array of ids)
在今后的Rails 3.2.0 ,你会写:
ids = Group.pluck(:id)
我不能等待; - )
I can't wait ;-)
这篇关于Rails的查询排序基于嵌套模型的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文