Rails - how do I change .new / .save to .create

I have two models: Schedule and Project. Project has_one Schedule and schedule belongs to_project. When I create a schedule, I do:

def create
  @schedule = Schedule.new(schedule_params)
  @schedule.project = Project.find(params[:project_id])
  if @schedule.save
    flash[:notice] = "Successfully created schedule."
    redirect_to profile_path(current_user)
  end
end

It works. However, I added an after_create callback and an after_update callback to create notifications. The “new schedule” notification when creating the schedule and the notification of your schedule has been updated after it was updated. The problem is that in the controller I use @ schedule.new and @ schedule.save, not @ schedule.create. I need to change my controller code to use .create so that the after_create callback will work. I already tried using the after_save callback, but it is called whenever the schedule is also updated, so this will not work.

Due to the way I define @schedule and @schedule, project, I cannot figure out how to change the code I have above to use @ schedule.create. Does anyone have any idea? Thank you

+2
source share
3 answers

after_createwill be started when the recording is saved for the first time, i.e. if @schedule.savesucceeds. There is no need to specifically change it as createinstead new.

+1
source

The method .createis either in the class:

http://apidock.com/rails/ActiveRecord/Base/create/class

For example, User.createbut not @user.create.

OR is in association:

@user.projects.create(params[:project])

after_create , Project User.

0

:

def create
    @project = Project.find(params[:project_id])
    if @project.schedule.create(schedule_params)
        flash[:notice] = "Successfully created schedule."
        redirect_to profile_path(current_user)
    end
end
0

All Articles