I am going to use the has_many :votes, :through => :links and sum functions.
For more information check:
so the solution is:
User table
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
Reference table
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
Vote table
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
User model
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
Link Model
class Link < ActiveRecord::Base belongs_to :user has_many :votes end
Voting model
class Vote < ActiveRecord::Base belongs_to :user belongs_to :link end
The trick is that you set the score to positive or negative, let them say β+1β for a positive vote and β-1β for a negative vote. NOTE. . Each vote is a record. The amount will be a total estimate.
How to use:
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
There are other functions that can be used, for example, the voice of a "trusted" user can dial +5 or -5, etc. etc.
Enjoy it!
source share