开发者

Tricky Association Question Rails

#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开发者_StackOverflow中文版 have voted on?

Thanks


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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜