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.
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.
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.
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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With