Rails模型回调(在创建/更新后)attribute_不起作用

And*_*pel 0 attributes model ruby-on-rails

我正在将Rails 5.1应用程序迁移到Rails 5.2.1。在我的模型中,我使用回调在创建或更新模型后创建活动日志。不幸的是todo.nametodo.name_was并且始终不变-当前值。这适用于每个属性和每个模型。还changed?返回false。

我想念什么吗?

非常感谢您的帮助!

Nim*_*pta 6

您将无法进入attribute_wasafter_create / update回调,因为此时数据库中的记录已更改。

您可以使用previous_changesin after_create/update回调。

这是下面的例子。

考虑,用户模型:

class User < ApplicationRecord

  before_update :check_for_changes
  after_update :check_for_previous_changes

  private def check_for_changes
    puts changes # => {"name"=>["Nimish Gupta", "Nimish Mahajan"], "updated_at"=>[Tue, 20 Nov 2018 00:02:14 PST -08:00, Tue, 20 Nov 2018 00:06:15 PST -08:00]}
    puts previous_changes # => {} At this point this will be empty beacuse changes are not made to DB yet
    puts name_was # => "Nimish Gupta" i.e the original name
    puts name # => "Nimish Mahajan" i.e the new name which will be going to save in DB
  end

  private def check_for_previous_changes
    puts changes # => {}
    # Please note `changes` would be empty now because record have been saved in DB now

    # but you can make use of previous_changes method to know what change has occurred.
    puts previous_changes # => {"name"=>["Nimish Gupta", "Nimish Mahajan"], "updated_at"=>[Tue, 20 Nov 2018 00:06:15 PST -08:00, Tue, 20 Nov 2018 00:08:07 PST -08:00]}

    puts name_was # => "Nimish Mahajan" i.e the new name which have been saved in DB
    puts name # => "Nimish Mahajan" i.e the new name which have been saved in DB

    # to get the previous name if after_create/update callback, Please use.
    puts previous_changes[:name][0]
  end

end

u = User.first # => #<User id: 1, name: "Nimish Gupta">
u.update(name: 'Nimish Mahajan') # => this will fire both before_update and after_update callbacks.
Run Code Online (Sandbox Code Playgroud)

希望这会帮助你。

您也可以查看答案以获取更多信息