Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-3.2

How does after_save work when saving an object


If I do the following:

@user.name = "John"    
@user.url = "www.john.com"
@user.save

If I use after_save

@user.url = "www.johnseena.com"
@user.save

What will happen when I do this?

I believe it should save the value because of the 'after_save' callback.


Solution

  • In my opinion, if you call save function in a after_save callback, then it will trap into a recursion unless you put a guard at the beginning. like this

    class User < AR::Base
          after_save :change_url
    
          def change_url
              #Check some condition to skip saving
              url = "www.johnseena.com"
              save              #<======= this save will fire the after_save again
          end
    end
    

    However, apart from putting a guard, you can use update_column also

    def change_url
        update_column(:url, "www.johnseena.com")
    end
    

    In this case it will not fire after_save. However, it will fire after_update. So if you have any update operation on that call back then you are in recursion again :)