I have a model called Vote and this is what vote.rb looks like:
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
(it is polymorphic because it also belongs to another model called Comment).
Each time a vote is created the value of total is updated. For example, Vote.create(:polarity => 2), will produce :polarity => 2, :total => 2
I just realize that this doesn’t make sense because :polarity will always equal to :total. What I actually want to do is to have the total to the model that Vote belongs to; in this case Post and Comment (Vote belongs to post and Post has many votes) so that each time a vote is created, the total column in the post will be updated. Like this:
May 13
Post.total = 3 (:id => 2)
Vote.polarity = 1 (:id => 1)
Vote.polarity = -1 (:id => 2)
Vote.polarity = 3 (:id => 3)
May 14
Post.total = 4 (:id => 2)
Vote.polarity = 1 (:id => 1)
Vote.polarity = -1 (:id => 2)
Vote.polarity = 3 (:id => 3)
Vote.polarity = 1 (:id => 4)
You need to update the total of the votable object in this way:
or you can use the conditional callback like @Sandip says: