Rails 数据库字段未正确更新
Rails db fields not updating properly
我正在尝试编写 get increment/decrement 方法来处理一个相当简单的 class 并且我 运行 遇到了一个奇怪的问题。如果我调用 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
每次实例化记录时都会调用 after_initialize
...这意味着新记录以及任何数据库检索。
如果您只想为新记录进行初始化,您可能需要更改初始化方法...
def init
self.points = 0 if new_record?
self.dms = 0 if new_record?
end
每次都会调用 init 函数,因此您的属性设置为 0。
来自 ruby 文档:
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
我正在尝试编写 get increment/decrement 方法来处理一个相当简单的 class 并且我 运行 遇到了一个奇怪的问题。如果我调用 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
after_initialize
...这意味着新记录以及任何数据库检索。
如果您只想为新记录进行初始化,您可能需要更改初始化方法...
def init
self.points = 0 if new_record?
self.dms = 0 if new_record?
end
每次都会调用 init 函数,因此您的属性设置为 0。
来自 ruby 文档:
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