Possible Duplicate:
What does ||= mean?
In this previous question, I asked about an effective way of associating Post, User, Comment and Vote models. The Vote model has a polarity column which stores the vote up (+1) and vote down (-1) values. It also has a total column which stores the sum of all the votes in posts and comments.
Someone gave me a detailed answer but I can’t understand this part (specially the self.total ||= 0 and self.total += self.polarity part and why 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
Can anyone explain the code above to me (I’m a Rails beginner)?
self.total ||= 0will set the value to 0 ifself.totalis nil or false. This would be good for the initial run when the model has just been created and no default value fortotalcolumn was defined. You don’t want to be doingnil + 1or anil - 1self.total += self.polarityis short form forself.total = self.total + self. polarityWhy
before_create, because it logically makes sense to have the proper values in place before attempting to write the database.Further reading: http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html