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> = "[email protected]"
=> "[email protected]"
irb(main):015:0> u.email_previously_changed?
=> true
irb(main):016:0> u.email_previous_change
=> ["[email protected]", "[email protected]"]
irb(main):017:0> = "[email protected]"
=> "[email protected]"
irb(main):019:0> u.email_previous_change
=> ["[email protected]", "[email protected]"]

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> = "[email protected]"
=> "[email protected]"
(0.2ms) begin transaction
SQL (0.7ms) UPDATE "users" SET "email" = ?, "updated_at" = ? WHERE "users"."id" = ? [["email", "[email protected]"], ["updated_at", 2017-02-08 19:21:31 UTC], ["id", 1]]
!--["[email protected]", "[email protected]"]--!
(26.7ms) commit transaction
=> true
irb(main):004:0> = "[email protected]"
=> "[email protected]"
(0.2ms) begin transaction
SQL (0.5ms) UPDATE "users" SET "email" = ?, "updated_at" = ? WHERE "users"."id" = ? [["email", "[email protected]"], ["updated_at", 2017-02-08 19:22:14 UTC], ["id", 1]]
!--["[email protected]", "[email protected]"]--!
(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 49,679+ 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.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.