Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails save method if no changes

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??

like image 582
j-dexx Avatar asked Jun 25 '14 15:06

j-dexx


1 Answers

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

like image 75
Dave Bryand Avatar answered Oct 17 '22 15:10

Dave Bryand