【问题标题】:Rails - how do I change .new/.save to .createRails - 如何将 .new/.save 更改为 .create
【发布时间】:2014-01-01 08:01:54
【问题描述】:

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

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 回调,但是每当计划更新时都会调用它,因此它不起作用。

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

【问题讨论】:

  • 每个人都很好地回答了这个问题,但答案基本上导致了我在这里发布的另一个非常相似的问题:stackoverflow.com/questions/20569839/…。我仍在阅读答案,很快我会为这个问题选出一名获胜者。

标签: ruby-on-rails ruby oop callback ruby-on-rails-4


【解决方案1】:

after_create 将在第一次保存记录后触发,即。如果@schedule.save 成功。无需专门将其更改为create 而不是new

【讨论】:

    【解决方案2】:

    试试这个:

    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】:

      .create 方法在类上:

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

      例如,User.create,而不是 @user.create

      它在一个关联上:

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

      如果你想在这里触发after_create回调,它需要定义在Project而不是User

      【讨论】:

      • 我已经从我的模型中调用了它们。我在问如何将控制器中的内容从 .new/.save 更改为 .create?
      • .create 是类方法,而不是实例方法。更新了我的答案。
      • 我正在按计划定义 after_create。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 2016-11-29
      • 2011-05-28
      • 1970-01-01
      相关资源
      最近更新 更多