Rails won't do an UPDATE
but it will run the after_save
callbacks even if nothing has changed:
pry $ u = User.first
=> #<User id: 1, email: "[email protected]", username: "dbryand"...
pry $ u.updated_at
=> Tue, 24 Jun 2014 18:36:04 UTC +00:00
pry $ u.changed?
=> false
pry $ u.save
From: /Users/dave/Projects/sample/app/models/user.rb @ line 3 :
1: class User < ActiveRecord::Base
2:
=> 3: after_save -> { binding.pry }
pry $ exit
=> true
pry $ u.updated_at
=> Tue, 24 Jun 2014 18:36:04 UTC +00:00
If you want to do something dependent on changes to a particular attribute in a before_save
, just do:
pry $ u = User.first
=> #<User id: 1, email: "[email protected]", username: "dbryand"...
pry $ u.save
=> true
pry $ u.name = "John Doe"
=> "John Doe"
pry $ u.save
From: /Users/dave/Projects/sample/app/models/user.rb @ line 3 :
1: class User < ActiveRecord::Base
2:
=> 3: before_save -> { binding.pry if name_changed? }
Dirty docs here: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
after_save
callback still has the dirty data attributes hash available for it. – Panpipe