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

2019-07-08 02:35发布

问题:

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

This works. However, I added an after_create callback and an after_update callback to make notifications. A 'new schedule created' notification when the schedule is created, and a 'your schedule has been updated' notification when it is 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 the after_create callback will work. I have already tried using the after_save callback, but that gets called whenever the schedule is updated as well so that won't work.

Because of 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 ideas? Thanks.

回答1:

after_create will be fired when after the record is saved for the first time, ie. if @schedule.save succeeds. There is no need to specifically change it to be create instead of new.



回答2:

Try this:

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


回答3:

The method .create is either on the class:

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

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

OR it is on an association:

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

If you want to trigger an after_create callback here, it needs to be defined on Project not on User.