繁体   English   中英

活动记录按关系和计数分组

[英]Active record group by relation and count

我有这些课

class Challenge
  has_many :photos
end

class Photo
  belong_to :challenge
  has_many :votes
end

class Vote
  belongs_to :photo
end

我试图为每张照片获得多少票。 我尝试

@challenge.photos.group_by(&:votes)

但是结果不是我所需要的...

为了轻松获取每张照片的票数,您可以在:photos名称:votes_count引入新列,并在Vote模型的belongs_to关联中添加counter_cache: true

class Vote
  belongs_to :photo, counter_cache: true
end

class AddVotesCountToPhotos < ActiveRecord::Migration
  def change
    add_column :photos, :votes_count, :integer
  end
end

现在,您可以轻松查询任何照片的票数:

@photo.votes_count

查找特定挑战的每张照片的投票的一种方法:

photos_with_votes = @challenge.photos.each_with_object([]) do |photo, arr|
  arr << [photo.id, photo.votes_count]
end

顺便说一句,由于您的表可能已经填充了记录,因此您需要使用SQL计数查询将所有计数器缓存重置为正确的值。 我们将为此目的使用reset_counters

Photo.pluck(:id).each { |id| Photo.reset_counters(id, :votes) }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM