在this前一个问题,我问了一下关联后,用户,评论和投票模型的有效途径。投票模式有一个极性列,其中存储了投票(+1)和投票下降(-1)值。它还有一个总计列,其中存储了帖子和评论中所有投票的总和。
有人给我一个详细的答案,但我不明白这个部分(特别是在self.total ||= 0
和self.total += self.polarity
一部分,为什么before_create
?):
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
before_create :update_total
protected
def update_total
self.total ||= 0
self.total += self.polarity
end
end
谁能解释一下上面我的代码(我一个Rails初学者)?
@Romain 46好,我实际上指的是整个代码(将特别着重于'|| =')。 – alexchenco 2012-02-03 11:32:15
有人劫持了这个头衔。 – alexchenco 2012-02-04 00:47:08