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

时间:2017-11-22 16:04:27

标签: ruby-on-rails activerecord rails-activerecord

我有这些课程

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)

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

1 个答案:

答案 0 :(得分:0)

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

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) }