2011-03-06 54 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

相关问题