Skip to main content

ActiveRecord

Tips • Asked by Sarah

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> u.email = "[email protected]"
=> "[email protected]"
irb(main):013:0> u.save
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> u.email = "[email protected]"
=> "[email protected]"
irb(main):018:0> u.save
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> u.email = "[email protected]"
=> "[email protected]"
irb(main):003:0> u.save
(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> u.email = "[email protected]"
=> "[email protected]"
irb(main):005:0> u.save
(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
ActiveModel::Dirty

after_update :what_changes?

def what_changes?
puts changes[:email].inspect
end

end


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.