views:

68

answers:

1
#Vote Model
belongs_to :voteable, :polymorphic => true
belongs_to :voter, :polymorphic => true

#votes table 
Voteid: integer, vote: boolean, voteable_id: integer, voteable_type: string, voter_id: integer, voter_type: string, created_at: datetime, updated_at: datetime

#User
  has_many :voteables, :foreign_key => :voter_id, :class_name => "Vote"
  has_many :votes, :foreign_key => :voter_id

#Vote_Item model 
acts_as_voteable
has_many :voters, :class_name => "Vote", :foreign_key => :voteable_id

Let's say 50 users have voted on VoteItem1, what's the best way to find out, what other VoteItem(s) a majority of those same 50 users have voted on?

Thanks

A: 

You're not too specific about what constitutes a majority. Something like this should return items voted for by a collection of users, from highest to lowest. You could add a condition where vote_count is greater than majority.

Vote_Item.find(:all, :joins => :votes, 
                     :select => "votes.*, count(votes) vote_count", 
                     :conditions => {:votes => {:user => @users}}, 
                     :group => "vote_items.id", :order => "vote_count desc")
mark
A majority is where out of those 50 who voted for VoteItem1, 47 voted for VoteItem2, 42 voted for VoteItem3 etc. So majority is not specific. It's defined as what other vote_item has max number of users from this set of voters. I am looking for a set of vote_items identified like this ordered by the number of users they have in common with this set of 50. Hope that makes sense. Thanks!
badnaam
Oh cool. What I posted above should work then. Let me know if it's confusing in its syntax or my answer is too brief.
mark
Mark, thank. There is no Voteable model here though
badnaam
Well, your Vote_Item model is voteable? :) I've edited my answer.
mark
thanks Mark. it throws an error, note there is no voter model or table, a user "acts_as_voter", voter_id in vote table is a user.id. http://pastie.org/1073971
badnaam
Ah sorry, misread that as well. :) Try replacing voters with votes as in new edit.
mark
I have updated the pastie with the error. http://pastie.org/1073971. Basically there is no votes.count in vote_items table. I have included the table description in the pastie, in case that is not clear
badnaam
The count isn't a column but a count of the number of vote rows. I was pretty sure that syntax was correct but obviously not. Try the answer now.
mark