本文介绍了Rails模型回调(在创建/更新后)attribute_不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am migrating a rails 5.1 app to rails 5.2.1. In my models I am using callbacks to create an activity log after a model was created or updated. Unfortunately todo.name and todo.name_was is always the same - the current value. This applies to every attribute and every model. Also changed? returns false.

我想念什么吗?

非常感谢您的帮助!

推荐答案

由于此时数据库中的记录已更改,因此在after_create/update回调中不会得到attribute_was.

You won't get attribute_was in after_create/update callback as the records has been changed in DB at this point.

您可以在after_create/update回调中使用previous_changes.

下面是一个例子.

考虑,用户模型:

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.

希望这会对您有所帮助.

Hope this will help you.

您还可以查看答案了解更多信息

You can also take a look at this answer for more information

这篇关于Rails模型回调(在创建/更新后)attribute_不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:33