2011-03-06 34 views
4

我有一個應用程序,它是一個簡單的reddit複製。使用Devise,您可以註冊並提交鏈接並對其進行投票。我開始嘗試vote_fu_rails_3,但有一個數據庫問題和其他一些麻煩,所以我用我自己的投票解決方案,它只記錄link_id,user_id和時間戳。Rails 3最好的方式來實現業力的想法?

我正在試圖實現一種方式,讓你的鏈接上的票數算上總「業力」分數,ala reddit。你的業力將會是你的正面投票減去你的負面投票總數。我想我需要在用戶模型中編寫一個方法(可能是鏈接模型?)

現在,用戶表中沒有用於'karma'或'link_score'或類似內容的字段。也許在鏈接表中添加一個簡單的整數列並在它投票時加入或減去它將允許我這樣做?

現在顯示我使用link.votes.count的票數,這可能是不正確的(也許它顯示總票數和總票數不是上下)。

Github Link

回答

2

我打算使用has_many :votes, :through => :links和sum方法的功能。

有關更多信息檢查:

所以這裏的解決方案:

用戶表

class CreateUsers < ActiveRecord::Migration 
    def self.up 
    create_table :users do |t| 
     t.string :name 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :users 
    end 
end 

錶鏈接

class CreateLinks < ActiveRecord::Migration 
    def self.up 
    create_table :links do |t| 
     t.integer :user_id 
     t.string :url 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :links 
    end 
end 

投票表

class CreateVotes < ActiveRecord::Migration 
    def self.up 
    create_table :votes do |t| 
     t.integer :user_id 
     t.integer :link_id 
     t.integer :score 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :votes 
    end 
end 

用戶模型

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

    def karma 
    self.votes.sum(:score) 
    end 

    def positive_votes 
    self.votes.sum(:score, :conditions => 'score > 0') 
    end 

    def negative_votes 
    self.votes.sum(:score, :conditions => 'score < 0') 
    end 

end 

鏈接型號

class Link < ActiveRecord::Base 
    belongs_to :user 
    has_many :votes 
end 

投票模式

class Vote < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :link 
end 

的技巧是,你設置的得分爲正值或負值讓我們說「+1」的積極投票和「-1」反對票。 注意:每票都是一個記錄。總和將是總分。

如何使用:

User.first.karma # gives you total karma 
User.first.positive_votes # gives you total positive votes 
User.first.negative_votes # gives you total negative votes 

還有其他的功能,你可以使用像一個「值得信賴」的用戶的一票可以得分+5或-5等等,等等

享受!

+0

這看起來不錯,但我必須做一些不正確的事情,只要將我的投票與鏈接和正在存儲的user_id關聯起來。讓我再玩一遍。你閒置一個IRC頻道嗎? – 2011-03-06 17:49:34

+0

我在freenode的#rails中接下來的2個小時,暱稱sled_ – sled 2011-03-06 18:06:26

2

如果你想它要快,爲什麼不加噶用戶模型,當有人票上/下更新呢?否則,每次顯示時都必須不斷計算。如果你得到很多用戶的業力,我認爲這是你的目標,那麼這可能會變得很昂貴。

+0

實際上這是一個簡單的查詢和數據庫查詢和計算。你的解決方案可能沒問題,但如果鏈接被刪除?該鏈接上的選票仍然在用戶的業力中。 – sled 2011-03-06 17:40:11

+0

@sled難道他不會有一個'after_destroy'回調重新計算業障嗎? – 2013-01-03 06:49:55

相關問題