开发者

Tricky Association Question Rails

开发者 https://www.devze.com 2023-01-10 05:56 出处:网络
#Vote Model belongs_to :voteable, :polymorphic => true belongs_to :voter, :polymorphic => true #votes table
#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

精彩评论

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