Finding the most in a has_many relationship with an extra condition

时间:2016-06-18 20:17:05

标签: ruby-on-rails has-many

I have a Users model that has many Polls. The Polls can be the same amongst users. The Poll model has many votes. The User Model also has many votes. The Vote model has User ID, Poll ID, and option chosen. I want to, for a given user, find the poll with the most votes.

I was looking counter_cache, but I'm not sure how to apply it to this problem. Is there a better way to solve this than iterating through each poll a user has and seeing the largest count where used_id = user_Id?

1 个答案:

答案 0 :(得分:0)

是的,您可以使用counter_cache执行此操作。在polls表格中,您有一列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

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

现在,要获得投票最多的投票,您可以轻松完成:

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

希望有所帮助。