Rails - 如何将.new / .save更改为.create [英] Rails - how do I change .new/.save to .create

查看:180
本文介绍了Rails - 如何将.new / .save更改为.create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:计划和项目。项目has_one计划和计划belongs_to项目。当我创建一个时间表,我做:

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

。但是,我添加了一个after_create回调和一个after_update回调来发送通知。创建计划时创建新计划已创建通知,更新后的您的计划已更新通知。问题是在控制器中我使用@ schedule.new和@ schedule.save,而不是@ schedule.create。我需要更改我的控制器代码使用.create所以after_create回调将工作。我已经尝试使用after_save回调,但是当调度每当计划更新,以至于不会工作。

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.

由于我定义@schedule和@ schedule,project的方式,我无法弄清楚如何更改我上面使用的代码@ schedule.create。有没有任何想法?谢谢。

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.

推荐答案

after_create 第一次,即。如果 @ schedule.save 成功。没有必要特别改变它为 create ,而不是 new

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.

这篇关于Rails - 如何将.new / .save更改为.create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆