2012-09-23 40 views
0

我有一个允许用户发布的应用程序。每篇文章都可以提高和降低投票率。每位用户的声望都是根据其帖子中的upvotes和downvotes计算出来的。现在,我在两个地方跟踪每个职位的投票和降薪。首先,有我的职位表:如何建模投票和反对投票?

create_table "posts", :force => true do |t| 
    t.integer "user_id" 
    t.text  "content" 
    t.integer "upvotes", :default => 0 
    t.integer "downvotes", :default => 0 
    t.datetime "created_at",    :null => false 
    t.datetime "updated_at",    :null => false 
    end 

我还跟踪每票使用一个单独的“票”表,让我知道哪些用户投票后已经(0票是没有票, 1投票是downvote,2票是给予好评):

create_table "votes", :force => true do |t| 
    t.integer "user_id" 
    t.integer "post_id" 
    t.integer "vote",  :default => 0 
    t.datetime "created_at",    :null => false 
    t.datetime "updated_at",    :null => false 
    end 

我原来一直跟踪的职位票两个不同的表,使其更有效地查询投票数的具体职位有,例如,这:

post_reputation = post.upvotes - post.downvotes 

但是,我现在认为这是不好的做法,我应该删除'posts'表上的'upvotes'和'downvotes'列,以便投票数据不重复。然后我会计算后的口碑做这样的事情:

def calculate_post_reputation(post_id) 
    some_post = Post.find(post_id) 
    vote_count = 0 
    some_post.votes.each do |vote| 
    if vote.vote.to_i == 2 
     vote_count += 1 
    elsif vote.vote.to_i == 1 
     vote_count -= 1 
    end 
    end 
    vote_count 
end 

是更好地保持“upvotes”和“downvotes”列或删除它们,并使用“票”表计算后的声誉?

回答

0

我会考虑(伪代码):

Models: 

class User < ActiveRecord::Base 
    has_many :votes 
    has_many :posts, :through => votes 

class Post < ActiveRecord::Base 
    has_many :votes 
    has_many :users, :though => :votes 

class Vote < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :post 
    attr_accessor :direction 
    UP='Up' 
    DOWN='Down' 
    DIRECTIONS=[UP,DOWN] 
    validates_inclusion_of :direction, in: [DIRECTIONS] 
    scope :up_votes where(:direction => UP) 
    scope :down_votes where(:direction => DOWN) 

然后使用Post.votes.up_votes.countPost.votes.down_votes.count为向上或向下票数。

您所概述的方法是我如何在SQL中处理它,以上是更多的rails风格方法。您需要添加适当的数据库迁移。