
我正试图在你的链接上实现投票的方式,以计入一个总的’业力’得分,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
> Ruby on Rails Guide on Calculations
所以这是解决方案:
用户表
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 endend
链接表
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 endend
投票表
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 endend
用户模型
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') endend
链接模型
class link < ActiveRecord::Base belongs_to :user has_many :Votesend
投票模型
class Vote < ActiveRecord::Base belongs_to :user belongs_to :linkend
诀窍在于你将得分设置为正值或负值,让积极投票为“1”,反对投票为“-1”.注意:每次投票都是记录.总和将是总分.
如何使用:
User.first.karma # gives you total karmaUser.first.positive_Votes # gives you total positive VotesUser.first.negative_Votes # gives you total negative Votes
您可以使用其他功能,例如“受信任”用户的投票可以获得5或-5等等.
请享用!
总结以上是内存溢出为你收集整理的ruby-on-rails – Rails 3实现业力思想的最佳方式?全部内容,希望文章能够帮你解决ruby-on-rails – Rails 3实现业力思想的最佳方式?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)