Ask A Question

Notifications

You’re not receiving notifications from this thread.

ActiveRecord

Sarah asked in Tips

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

Reply

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 = "test1@gmail.com"
=> "test1@gmail.com"
irb(main):013:0> u.save
irb(main):015:0> u.email_previously_changed?
=> true
irb(main):016:0> u.email_previous_change
=> ["test@gmail.com", "test1@gmail.com"]
irb(main):017:0> u.email = "test3@gmail.com"
=> "test3@gmail.com"
irb(main):018:0> u.save
irb(main):019:0> u.email_previous_change
=> ["test1@gmail.com", "test3@gmail.com"]

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.

Reply

ok

Reply

Alright further testing:

=> #
irb(main):002:0> u.email = "test1@gmail.com"
=> "test1@gmail.com"
irb(main):003:0> u.save
(0.2ms) begin transaction
SQL (0.7ms) UPDATE "users" SET "email" = ?, "updated_at" = ? WHERE "users"."id" = ? [["email", "test1@gmail.com"], ["updated_at", 2017-02-08 19:21:31 UTC], ["id", 1]]
!--["test@gmail.com", "test1@gmail.com"]--!
(26.7ms) commit transaction
=> true
irb(main):004:0> u.email = "test2@gmail.com"
=> "test2@gmail.com"
irb(main):005:0> u.save
(0.2ms) begin transaction
SQL (0.5ms) UPDATE "users" SET "email" = ?, "updated_at" = ? WHERE "users"."id" = ? [["email", "test2@gmail.com"], ["updated_at", 2017-02-08 19:22:14 UTC], ["id", 1]]
!--["test1@gmail.com", "test2@gmail.com"]--!
(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

Reply
Join the discussion
Create an account Log in

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

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

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