我有两个型号:Group& GroupMember
我想返回群组,按最高的GroupMember计数排序?如何在Rails中设置这种类型的连接/查询计数?
答案 0 :(得分:2)
使用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
仅一个查询,仅在组表上。
修改强>
如果您需要重置group_members_count:
ids = Group.select(:id).map &:id
ids.each do |id|
Group.reset_counters(id, :group_members)
end
(因为reset_counters不接受一组id)
将来Rails 3.2.0,你会写:
ids = Group.pluck(:id)
我等不及了; - )
答案 1 :(得分:1)
class Group < ActiveRecord::Base
has_many :group_members
default_scope order('(select count(1) from group_members where group_members.group_id = groups.id) desc')
end
请注意,这会在您的订单子句中创建一个子查询,这可能会导致包含许多组记录的重要SQL减速。如果频繁使用此信息,最好有一个计数器缓存,如Delba建议的那样。