All threads / ActiveRecord
Ask A Question


You’re not receiving notifications from this thread.


Sarah asked in Tips

Rails console:
Memoization seems to be a pretty awesome resource.

Hi Sarah,

I felt I should help since I was helping you last week on Slack.

I went ahead and did some testing with ActiveModel::Dirty for your scenario.

Here's some output from rails console:

irb(main):009:0> = ""
=> ""
irb(main):015:0> u.email_previously_changed?
=> true
irb(main):016:0> u.email_previous_change
=> ["", ""]
irb(main):017:0> = ""
=> ""
irb(main):019:0> u.email_previous_change
=> ["", ""]

Each time the object is saved the ActiveModel::Dirty will track the changes and return the proper updated "new" old email. I think it's still working as you need it. The first email in the array is always the old email that you want to send the confirmation to.

Alright further testing:

=> #
irb(main):002:0> = ""
=> ""
(0.2ms) begin transaction
SQL (0.7ms) UPDATE "users" SET "email" = ?, "updated_at" = ? WHERE "users"."id" = ? [["email", ""], ["updated_at", 2017-02-08 19:21:31 UTC], ["id", 1]]
!--["", ""]--!
(26.7ms) commit transaction
=> true
irb(main):004:0> = ""
=> ""
(0.2ms) begin transaction
SQL (0.5ms) UPDATE "users" SET "email" = ?, "updated_at" = ? WHERE "users"."id" = ? [["email", ""], ["updated_at", 2017-02-08 19:22:14 UTC], ["id", 1]]
!--["", ""]--!
(30.9ms) commit transaction
=> true

!-- output --! designates the after_update callback outputting the change value.

class User < ApplicationRecord

after_update :what_changes?

def what_changes?
puts changes[:email].inspect


Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 68,326+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.