【问题标题】:Tricky Association Question Rails棘手的关联问题 Rails
【发布时间】:2010-08-03 17:57:28
【问题描述】:
#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

假设有 50 位用户对 VoteItem1 进行了投票,那么最好的方法是找出这 50 位用户中的大多数投票的其他 VoteItem 是什么?

谢谢

【问题讨论】:

    标签: ruby-on-rails associations polymorphic-associations


    【解决方案1】:

    您对什么构成多数并不太具体。像这样的东西应该返回由一组用户投票的项目,从最高到最低。您可以添加一个投票计数大于多数的条件。

    Vote_Item.find(:all, :joins => :votes, 
                         :select => "votes.*, count(votes) vote_count", 
                         :conditions => {:votes => {:user => @users}}, 
                         :group => "vote_items.id", :order => "vote_count desc")
    

    【讨论】:

    • 多数是在投票给 VoteItem1 的 50 人中,有 47 人投票给 VoteItem2,42 人投票给 VoteItem3 等等。所以多数并不具体。它被定义为其他 vote_item 在这组选民中拥有的最大用户数。我正在寻找一组像这样标识的 vote_items,按照他们与这组 50 个共有的用户数量排序。希望这是有道理的。谢谢!
    • 太酷了。我在上面发布的内容应该可以工作。让我知道它的语法是否令人困惑或我的回答太简短。
    • 那么,您的 Vote_Item 模型是可投票的吗? :) 我已经编辑了我的答案。
    • 谢谢马克。它抛出一个错误,注意没有投票者模型或表,用户“acts_as_voter”,投票表中的voter_id是一个user.id。 pastie.org/1073971
    • 对不起,我也误读了。 :) 尝试用新编辑中的投票替换选民。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2011-07-23
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多