ruby-on-rails – Rails 3实现业力思想的最佳方式?
发布时间:2020-12-17 02:28:35 所属栏目:百科 来源:网络整理
导读:我有一个应用程序,它是reddit的简单克隆.使用Devise,您可以注册并提交链接并对其进行投票.我开始尝试使用vote_fu_rails_3但是遇到了数据库问题和其他一些问题,所以我选择了自己的投票解决方案,它只记录了link_id,user_id和时间戳. 我正试图在你的链接上实现
我有一个应用程序,它是reddit的简单克隆.使用Devise,您可以注册并提交链接并对其进行投票.我开始尝试使用vote_fu_rails_3但是遇到了数据库问题和其他一些问题,所以我选择了自己的投票解决方案,它只记录了link_id,user_id和时间戳.
我正试图在你的链接上实现投票的方式,以计入一个总的’业力’得分,ala reddit.你的业力将是你的正面投票,而不是你的负面投票.我想我需要在User模型中编写一个方法(也许是链接模型?) 现在用户表中没有“karma”或“link_score”或类似的字段.也许在Link表中添加一个简单的整数列,并在其投票时添加或减去它将允许我这样做? 现在显示我正在使用link.votes.count的投票数可能不正确(也许它显示总票数而不是总票数为Up – Down). Github Link 解决方法
我将使用has_many:votes,:through =>的功能. :链接和sum方法.
有关其他信息,请检查 > Ruby on Rails Guide on Associations 所以这是解决方案: 用户表 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等等. 请享用! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |