2012-09-23 39 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風格方法。您需要添加適當的數據庫遷移。