在具有额外条件的 has_many 关系中找到最多

Finding the most in a has_many relationship with an extra condition

我有一个包含许多投票的用户模型。用户之间的民意调查可以相同。 Poll 模型有很多选票。用户模型也有很多选票。投票模型选择了用户 ID、投票 ID 和选项。我想为给定用户找到得票最多的投票。

我正在寻找 counter_cache,但我不确定如何将其应用于此问题。有没有更好的方法来解决这个问题,而不是遍历用户拥有的每个民意调查并查看 used_id = user_Id?

的最大计数

是的,您可以使用 counter_cache 来做到这一点。在 polls table 上,您将有一列 votes_count。您的迁移可能如下所示:

add_column :polls, :votes_count, :integer, default: 0

查找记录的方法是:

class User
  has_many :polls
  has_many :votes
end

class Poll
  has_many :votes
end

class Vote
  belongs_to :user
  belongs_to :poll, counter_cache :true
  ##attr :option_chosen
end

如果您在添加 table 之前有一些记录,您需要重置计数器。

现在,要获取得票最多的投票,您可以轻松地执行以下操作:

User.first.polls.order(votes_count: :desc).first

希望对您有所帮助。