두 모델이 있습니다. 그룹 & GroupMember중첩 모델의 개수에 따라 정렬하는 레일스 쿼리입니까?
그룹을 가장 높은 GroupMember 수로 정렬하여 반환하고 싶습니다. Rails에서 이러한 유형의 조인/쿼리 수를 어떻게 설정합니까?
두 모델이 있습니다. 그룹 & GroupMember중첩 모델의 개수에 따라 정렬하는 레일스 쿼리입니까?
그룹을 가장 높은 GroupMember 수로 정렬하여 반환하고 싶습니다. Rails에서 이러한 유형의 조인/쿼리 수를 어떻게 설정합니까?
인생은 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 재설정해야하는 경우
: 미래 Rails 3.2.0에서
(reset_counters는 ID의 배열을 고려하지 않기 때문에)
ids = Group.select(:id).map &:id
ids.each do |id|
Group.reset_counters(id, :group_members)
end
을, 당신이 쓰는 것입니다 :
ids = Group.pluck(:id)
414,나는이 많은 그룹 레코드가 중요한 SQL 둔화를 생성 할 수있는 주문 절 안에 하위 쿼리를 생성하는 ;-)
감사하지만 지금은 여러 가지 이유로 그것을 피하고 싶습니다. 이것이 Rails로 어떻게 할 수 있습니까? 유용한 reset_counters 코드에 대해 – AnApprentice
+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
참고 기다릴 수 없습니다. 이 정보가 자주 사용되는 경우 델바가 제안하는대로 카운터 캐시를 갖는 것이 좋습니다.
누구든지 아이디어가 있습니까? – AnApprentice