Вы не получите attribute_was
в обратном вызове after_create / update, так как на этом этапе записи были изменены в БД.
Вы можете использовать previous_changes
в 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.
Надеюсь, это поможет вам.
Вы также можете взглянуть на этот ответ для получения дополнительной информации