Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 858
SSP Avatar asked Oct 11 '12 08:10

SSP


People also ask

How do rails Callbacks work?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

What is after_ save in rails?

Rails provides ActiveRecord callbacks to perform an action after a record is updated in the database. But, when to use after_commit vs after_save really depends on the activities that need to be done in these callbacks.


2 Answers

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 :)

like image 137
Samiron Avatar answered Oct 23 '22 01:10

Samiron


The after_save callback will be triggered irrespective its a save or an update on that object.

Also,

update_column doesn't trigger any callbacks(ie after_update) and skips validations too. see http://apidock.com/rails/ActiveRecord/Persistence/update_column

U should specifically use after_create or after_update depending upon the operation and its timing.

after_create :send_mail
def send_x_mail
  #some mail that user has been created
end

after_update :send_y_mail
def send_y_mail
  #some data has been updated
end

after_save :update_some_date
def update_some_data
  ...
  action which doesnt update the current object else will trigger the call_back
end

Also see What is the difference between `after_create` and `after_save` and when to use which? and for callbacks see http://ar.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M000059

like image 32
prasad.surase Avatar answered Oct 23 '22 01:10

prasad.surase