【问题标题】:Rails db fields not updating properlyRails 数据库字段未正确更新
【发布时间】:2016-01-09 01:42:09
【问题描述】:

我正在尝试为一个相当简单的类编写获取增量/减量方法,但我遇到了一个奇怪的问题。如果我调用 give_point(),点数会增加到 1,然后一遍又一遍地调用它没有任何反应。然后,如果我全部给定_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 :init ......你是finding 调用givetake 之间的记录吗?如果您在User 模型中具有相同的after_initialize,则用户记录也将在每个.find 上初始化为零(包括您在Post 模型中所做的.finds)。
  • 您是否知道每次实例化记录时都会调用after_initialize?这与new 以及任何数据库检索有关。您可能想对 dms 列执行 self.points = 0 if new_record? 和同上...所以当您检索现有记录时不会发生这种情况。
  • 啊,酷。让我把它放在一个答案中,这样你就可以接受了。

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


【解决方案1】:

每次实例化记录时都会调用after_initialize...这意味着新记录以及任何数据库检索。

如果您只想初始化新记录,您可能需要更改 init 方法...

def init
  self.points = 0 if new_record?
  self.dms = 0 if new_record?
end

【讨论】:

    【解决方案2】:

    每次都会调用 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

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      相关资源
      最近更新 更多