I'm trying to write get increment/decrement methods working for a fairly simple class and im running into a strange issue. If i call give_point(), points get incremented to 1, then calling it over and over again nothing happens. Then if i all give_dm(), points gets reset to 0 and dms gets set to 1... I can't get it to keep incrementing and they keep resetting each other in my database. Can anyone point me in the right direction? I have no idea what's wrong and I've been staring at this for quite some time now. Thanks for any help ahead of time!
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :group
validates :content, :presence => true
after_initialize :init
def init
self.points = 0
self.dms = 0
end
def give_point()
self.points += 1
update(points: self.points)
end
def take_point()
self.point -= 1
update(points: self.points)
end
def give_dm()
self.dms += 1
update(dms: self.dms)
end
def take_dm()
self.dms -= 1
update(dms: self.dms)
end
end
after_initialize
is called every time a record is instantiated... this means both new records but also with any db retrievals.
If you only want to initialize for new records, you may want to change the init method...
def init
self.points = 0 if new_record?
self.dms = 0 if new_record?
end