我试图编写获取递增/递减方法,为一个相当简单的类工作,并遇到一个奇怪的问题。如果我调用give_point(),则点数会增加到1,然后一遍又一遍地调用它,没有任何反应。然后,如果我所有的give_dm(),点被重置为0并且dms被设置为1 ...我不能让它继续递增并且它们在我的数据库中保持相互重置。谁能指出我正确的方向?我不知道出了什么问题,而且我已经盯着这一段很长一段时间了。谢谢你提前帮忙!
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
答案 0 :(得分:2)
after_initialize
...这意味着既有新记录,也有任何数据库检索。
如果您只想初始化新记录,可能需要更改init方法......
def init
self.points = 0 if new_record?
self.dms = 0 if new_record?
end
答案 1 :(得分:0)
每次调用init函数,因此您的属性设置为0 来自ruby docs:
after_find and after_initialize callback is triggered for each object that is found and instantiated by a finder, with after_initialize being triggered after new objects are instantiated as well.
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html