Rails数据库字段未正确更新

时间:2016-01-09 01:42:09

标签: ruby-on-rails ruby database activerecord models

我试图编写获取递增/递减方法,为一个相当简单的类工作,并遇到一个奇怪的问题。如果我调用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

2 个答案:

答案 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