ActiveRecord: How to return counts of distinct votes?
My data model: Users, Votes, Items
Users can vote many times on an ite开发者_如何学编程m
I want to return the total number of up and down votes for an item, only counting the most recent one for a given user
I was thinking something like selecting a distinct user_id and grouping by the value of the vote, but I'm not sure how I'd make the distinct pick up the most recent one..
I'd prefer to do this through the Rails 3 finder methods..
Soution 1.
What about a mix of counter_cache and, inside your Item model
has_many :up_votes, :class_name => "Vote", :conditions => {:condition_for_upvote => true}, :dependent => :destroy
has_many :down_votes, :class_name => "Vote", :conditions => {:condition_for_upvote => false}, :dependent => :destroy
You can order up and down votes by created_at
.
Soution 2.
You can also use scopes crafting them to your specific ordering needs inside your Vote model and counting them after retrieving.
精彩评论