Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - after_update occurring on .save for new object

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
like image 951
Philip7899 Avatar asked Dec 12 '13 22:12

Philip7899


1 Answers

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.

like image 103
fivedigit Avatar answered Nov 18 '22 12:11

fivedigit