使用vote_fuplugin。它支持以下方法:
user.vote_count # all votes
user.vote_count(true) # votes for
user.vote_count(false) # votes against
posts.votes_count # all vote count
posts.votes_for # votes for
posts.votes_against # votes against
posts.votes_total # votes total
如果您不想使用该插件,那么我将按如下方式处理您的场景:
我假设模型之间存在以下关系。
class User < ActiveRecord::Base
has_many :posts
has_many :votes, :through => :posts
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :votes
end
class Vote < ActiveRecord::Base
belongs_to :post
end
1.1) 统计所有用户的投票
Vote.count # all
Vote.count(:conditions => {:vote => true}) # all for
Vote.count(:conditions => {:vote => false}) # all against
1.2) 查找用户的投票
user.votes.count # all
user.votes.count(:conditions => {:vote => true}) # all for
user.votes.count(:conditions => {:vote => false}) # all against
2.1) 投票最多的用户
# You can add the limit clause to restrict the rows
User.find(:all, :select => "users.*, count(votes.id) AS count",
:joins => [:posts, :votes],
:conditions => [" votes.vote = ? ", true],
:group => "votes.id", :order => "count DESC")
2.2) 投票最多的帖子
# You can add the limit clause to restrict the rows
Post.find(:all, :select => "posts.*, count(votes.id) AS count",
:joins => [:votes],
:conditions => [" votes.vote = ? ", true],
:group => "votes.id", :order => "count DESC")
3.1 ) 对于一个用户的总票数
参考1.2.1