What is the difference between `after_create` and `after_save` and when to use which?

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


Are after_create and after_save the same as per functionality?

I want to do an operation with the email of a user after its account creation.

I want to do that operation when it is saved in the database.

which is preferable to use: after_create or after_save?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

after_create only works once - just after the record is first created.

after_save works every time you save the object - even if you're just updating it many years later

So if you want to do this email operation only just the once (and then never again) then use after_create.

If you want to do it every time the object is saved, then do it in after_save

Solution 2 - Ruby on-Rails

From the docs:

> after_create() > > Is called after > Base.save on new objects that haven‘t > been saved yet (no record exists). > > after_save() > > Is called after Base.save > (regardless of whether it‘s a create > or update save).

Solution 3 - Ruby on-Rails

after_save()

Works fine when you have to save models that do not save very often. For this particular example of changing records frequently it would be advisable to use

 after_commit()

make sure that the model is saved in the database before the action is executed after_commit :calculate_credit_score

def calculate_credit_score
     #Call a Cron job
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSwapnil ChincholkarView Question on Stackoverflow
Solution 1 - Ruby on-RailsTaryn EastView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMichael KohlView Answer on Stackoverflow
Solution 3 - Ruby on-RailspensebienView Answer on Stackoverflow