133

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?

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Swapnil Chincholkar
  • 2,869
  • 3
  • 22
  • 22

3 Answers3

223

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

Taryn East
  • 27,486
  • 9
  • 86
  • 108
  • 3
    readers should note that, [according to the docs](https://api.rubyonrails.org/v5.1/classes/ActiveRecord/Relation.html#method-i-update_all), ActiveRecord's `update_all` does not invoke any callbacks, including `after_*` – sam-6174 Jan 10 '20 at 19:34
97

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

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
1
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
pensebien
  • 506
  • 4
  • 16
  • You advise to use `after_commit` but don't explain why. Please can you elaborate? Note that `after_commit` runs on create, updat and destroy. Docs: https://apidock.com/rails/ActiveRecord/Transactions/ClassMethods/after_commit So it is not the same behavior as `after_save` You really want to call that cron_job after after destroying the record? Or in the ops case, send an email to a now deleted user? Be careful with using `after_commit` – rmcsharry Jul 01 '19 at 15:33
  • `after_commit` runs on those CRUD operations, so if in his case the email is updated often, then it would be easier to combine the action for a specific callback. In my case I used `after_commit : calculate_profile_update, on: :update` – pensebien Nov 28 '19 at 09:05