0

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)?

Community
  • 1
  • 1
alexchenco
  • 53,565
  • 76
  • 241
  • 413

2 Answers2

2

self.total ||= 0 means if self.total is no value(nil), it will set value to 0

Hope it will help, I will try my best to help you let me think for the others.

For ||= do, I think this link will be useful for you->http://railscasts.com/episodes/1-caching-with-instance-variables

piam
  • 653
  • 6
  • 13
2
  1. self.total ||= 0 will set the value to 0 if self.total is nil or false. This would be good for the initial run when the model has just been created and no default value for total column was defined. You don't want to be doing nil + 1 or a nil - 1

  2. self.total += self.polarity is short form for self.total = self.total + self. polarity

  3. Why 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

Anand Shah
  • 14,575
  • 16
  • 72
  • 110