更新方法没有从编辑方法获取表单输入

时间:2014-07-30 07:21:46

标签: ruby-on-rails ruby

我正在尝试创建和更新合同。 create工作正常。但我的更新采用默认值而不是编辑中的值。为什么?我的结束日期始终是开始日期的下一年。

 before_filter :only => :create do
   @contract = Contract.new(params[:contract])
     if @contract.start_date.present?
       n = @contract.num_years
       n = n.blank? ? 1 : n.to_i
       @contract.end_date = @contract.start_date + n.years - 1.day
     end
   @contract.save!
   Mailers.delay(queue: "Mailers").contract_created_notification(@contract)
 end
 controller do
   def update
    @contract = Contract.find(params[:id])
     if @contract.start_date.present?
       n = @contract.num_years
       n = n.blank? ? 1 : n.to_i
       @contract.end_date = @contract.start_date + n.years - 1.day
       update!
       Mailers.delay(queue: "Mailers").contract_created_notification(@contract)
     end
   end

日志文件:

  

INSERT INTO delayed_jobsattemptscreated_atfailed_athandlerlast_errorlocked_at,{{1 }},locked_bypriorityqueuerun_at)VALUES(0,'2014-07-30 06:41:57',NULL,'--- !ruby / object:Delayed :: PerformableMailer \ nobject:!ruby / class \'Mailers \'\ nmethod_name :: contract_created_notification \ nargs:\ n-!ruby / ActiveRecord:Contract \ n attributes:\ n id:464 \ n school_id :370 \ n start_date:2014-07-01 \ n end_date:2022-06-30 \ n num_students:900 \ n pymt_status:false \ n created_at:& 1 2014-07-30 06:41:57.876186386 Z \ n updated_at:* 1 \ n',NULL,NULL,NULL,0,'Mailers','2014-07-30 06:41:57','2014-07-30 06:41:57')

updated_at

1 个答案:

答案 0 :(得分:0)

奇怪的控制器代码

我最初的注意力来自:

before_filter :only => :create do

controller do

这些究竟是什么?它们看起来不像典型的Rails控制器代码:

-

#app/controllers/contracts_controller.rb
Class ContractsController < ApplicationController
   before_action :set_vars, only: [:edit, :update]

   def new
      @contract = Contract.new
   end

   def create
      @contract = Contract.new(contract_params)
      @contract.set_date if @contract.start_date.present?
      @contract.save
   end

   def update
      @contract.set_date if @contract.start_date.present?
      @contract.update(contract_params)
   end

   private

   def set_vars
       @contract = Contract.find params[:id]
   end

   def set_date
       n = self.num_years
       n = n.blank? ? 1 : n.to_i
       self.end_date = self.start_date + n.years - 1.day
   end

   def contract_params
      params.require(:contract).permit(:contract, :attributes)
   end
end

<强>日期

虽然我不确定如何解决您的问题,但我认为将控制器排序将是第一步。

如果您想根据end_date属性设置num_years,我建议您必须考虑edit方法&#39}传递num_years属性,然后您可以将其传递给update操作