I have two models: UserNotification and Schedule. When a schedule is created, one type of user notification is created (the first line of code). When a schedule is updated, another type of user notification is created (the second line of code). For some reason, after_update is occurring after a save (i only want it to happen after an update). Here is code in code:
class Schedule < ActiveRecord::Base
after_save 'UserNotification.schedule_created(@user)'
after_update 'UserNotification.schedule_updated(@user)'
end
Am I missing something. How do I get after_save to only happen after I say @schedule.save and after_update to only occur after I do @schedule.update_attributes(...) ? Here is the controller code if it helps:
if @schedule.save
flash[:notice] = "Successfully created schedule."
redirect_to profile_path(current_user.profile_name) #change to project path later
end
Under the hood, save
calls create
on a new record, and update
on a persisted record.
The after_save
callback is called both when a record has been created and updated.
The after_create
and after_update
callbacks are called on new and persisted record respectively.
You'd need to change your after_save
callback to after_create
if you only want it to run after creating an object.
More on ActiveRecord callbacks can be found in the Rails documentation.
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