我正在尝试创建和更新合同。 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_jobs
(attempts
,created_at
,failed_at
,handler
,last_error
,locked_at
,{{1 }},locked_by
,priority
,queue
,run_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
答案 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
操作