Home > Software engineering >  Rails Model After Update Get Changes
Rails Model After Update Get Changes

Time:11-15

I'm working with an analytics like system and would like to send model attribute changes to it whenever they occur

Assuming I have something like this:

after_update :my_update_method
def my_update_method
   #send update changes to analytics system
end

Is there a way within my_update_method to get what model attributes changed? Vs. sending the entire model every time which seems inefficient

CodePudding user response:

you can select your rails version first and try https://jetrockets.com/blog/rails-5-2-changes-in-callbacks

ex :

class Book
 after_update :my_update_method
 def my_update_method
  #send update changes to analytics system in Case Rails 5
  values = saved_changes
  p values
 end
end

Book.last.update(title: "Hello")
# Output 
{"title"=>["s", "Hello "], "updated_at"=>[Sun, 13 Nov 2022 22:34:33 UTC  00:00, Sun, 13 Nov 2022 22:37

Good luck

  • Related