Bogdan Gusiev
Bogdan Gusiev

Reputation: 8305

Rails: check if the model was really saved in after_save

ActiveRecord use to call after_save callback each time save method is called even if the model was not changed and no insert/update query spawned.

This is the default behaviour actually. And that is ok in most cases.

But some of the after_save callbacks are sensitive to the thing that if the model was actually saved or not.

Is there a way to determine if the model was actually saved in the after_save?

I am running the following test code:

class Stage < ActiveRecord::Base
  after_save do
    pp changes
  end
end

s = Stage.first
s.name = "q1"
s.save!

Upvotes: 7

Views: 18682

Answers (3)

pdenya
pdenya

Reputation: 485

For anyone else landing here, latest rails 5 has a model method saved_changes? and a corresponding method saved_changes which shows those changes.

book = Book.first
book.saved_changes?
=> false

book.title = "new"
book.save

book.saved_changes?
=> true
book.saved_changes
=> {"title" => ["old", "new"]},

Upvotes: 0

boulder_ruby
boulder_ruby

Reputation: 39763

After a save, check to see if the object saved is a new object

a = ModelName.new
a.id = 1
a.save
a.new_record?
#=> false

Upvotes: 7

Simone Carletti
Simone Carletti

Reputation: 176552

ActiveRecord use to call after_save callback each time save method is called even if the model was not changed and no insert/update query spawned.

ActiveRecord executes :after_save callbacks each time the record is successfully saved regardless it was changed.

# record invalid, after_save not triggered
Record.new.save

# record valid, after_save triggered
r = Record.new(:attr => value)

# record valid and not changed, after_save triggered
r.save

What you want to know is if the record is changed, not if the record is saved. You can easily accomplish this using record.changed?

class Record

  after_save :do_something_if_changed

  protected

  def do_something_if_changed
    if changed?
      # ...
    end
  end
end

Upvotes: 8

Related Questions