fguillen
fguillen

Reputation: 38772

ActiveRecord callback after_save not really called after saved

Having this:

class User < ActiveRecord::Base
  after_save :execute_after_save

  def execute_after_save
    Kernel.puts "Actual object still not saved" if changed?
  end
end

The Kernel.puts sentence should be called never because after the object is saved it is not changed.

1.9.3p286 :003 > u = User.create!(:name => "Wadus Name")
Actual object still not saved
 => #<User id: 1, name: "Wadus Name"> 
1.9.3p286 :004 > u.changed?
 => false 
1.9.3p286 :004 > u.name = "Other Name"
 => "Other Name" 
1.9.3p286 :005 > u.changed?
 => true 
1.9.3p286 :006 > u.save!
Actual object still not saved
 => true 
1.9.3p286 :007 > u.changed?
 => false 

See all the Actual object still not saved sentences that shouldn't be there.

I was expecting that the after_save callback is actually called after the object is saved.

This situation is turning me crazy with some combinations of dirty objects and callbacks that I have to do.

Upvotes: 2

Views: 1663

Answers (1)

Tatiana Potetinova
Tatiana Potetinova

Reputation: 141

It's after save but before commit.

after_commit might be something you're looking for.

Upvotes: 8

Related Questions