如何在ROR中从编辑表单中获取参数?

时间:2014-08-06 11:24:29

标签: ruby-on-rails

我正在创建一个项目,该项目使用活动管理员为用户创建合同。我必须使用start_date和合同年数(年数)来计算合同的最后日期。它适用于新合同的创建。但是为了更新,我正在更改开始日期和年份,它不采用start_edit(表单输入)。 注意:我无法使用开始日期更改合同。

  ActiveAdmin.register Contract do

  menu false
  config.batch_actions = true

index do
id_column
column :start_date
column :end_date
 actions defaults: true do |contract|
 link_to 'Archive', archive_active_admin_contract_path(contract)
 end
end

filter :start_date
filter :num_years

form  do |form|
form.inputs do

  if form.object.new_record?
    form.input :num_years, :label => "No. of Years", :required => true
  else
   form.input :num_years, :label => "No. of Years", :required => true, :input_html => {:value => "#{Contract.contract_year(params[:id])}"}
  end

  form.input :start_date, :label => "Contract Start Date", :required => true, :discard_day => true , :include_blank => false
 end

form.actions :commit
end
 before_filter :only => [:create, :update] do

  if self.action_name.to_sym == :create
   @contract = Contract.new( params[:contract] )
  else
  @contract = Contract.find( params[:id] )
 end

 if @contract.start_date.present?
  n = params[:contract][:num_years]
  n = n.blank? ? 1 : n.to_i
  @contract.end_date = @contract.start_date + n.years - 1.day
end
end

def update
  flash[:notice] = 'Contract has been created successfully!'
  update!do |format|
    format.html { redirect_to user_path }
  end

1 个答案:

答案 0 :(得分:0)

我将编码从控制器更改为通过以下代码对其工作进行建模

before_save :calculate
def calculate
n = self.num_years
n = n.blank? ? 1 : n.to_i
self.end_date = self.start_date + n.years
end