Rails save method if no changes
Asked Answered
P

1

20

I seem to remember reading somewhere that rails won't commit to the database if no attributes have been changed (presumably as part of active record dirty) is this the case? I can't seem to find it and am none the wiser having had a quick look through the source code.

If this is false I need to use a before_save callback because I want to run some code based on whether or not a change has occured.

I assume after_save with dirty data won't work??

Panpipe answered 25/6, 2014 at 15:20 Comment(0)
A
30

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

Ayurveda answered 25/6, 2014 at 15:40 Comment(1)
Thanks, I looked at the Dirty documentation but elsewhere on SO people have said the after_save callback still has the dirty data attributes hash available for it.Panpipe

© 2022 - 2024 — McMap. All rights reserved.