我打算使用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等等,等等
享受!
这看起来不错,但我必须做一些不正确的事情,只要将我的投票与链接和正在存储的user_id关联起来。让我再玩一遍。你闲置一个IRC频道吗? – 2011-03-06 17:49:34
我在freenode的#rails中接下来的2个小时,昵称sled_ – sled 2011-03-06 18:06:26