Active Admin的强参数:没有将Symbol隐式转换为Integer

时间:2014-12-10 10:17:58

标签: ruby-on-rails activeadmin strong-parameters

我使用的是Rails 4并使用Active Admin。我需要为createupdate方法提供一组不同的参数,所以我通过修改instructions from the Active Admin documentation来接近这一点。这是我想要做的:

我的模型需要在create上采用以下参数:

:name, :region, :contact_details, :province_id, :status_id, :start_date

但是不应该在更新时更改:region。因此,如果不覆盖默认的Active Admin的更新方法,我将修改permit_params,如下所示:

  permit_params do
    params = [:name, :contact_details, :province_id, :status_id, :start_date]
    params.push(:region) unless params[:action] == "update"
    params
  end

结果不可避免地出现以下错误:

TypeError: no implicit conversion of Symbol into Integer
我相信,当permit_params创建方法permitted_params时,会发生

我做错了什么?解决方案是什么?

3 个答案:

答案 0 :(得分:2)

Andrey Deineko的缩短版

 permit_params do
    params = [:region, :name, :contact_details, :province_id, :status_id, :start_date]
    params.delete(:region) if action_name == 'update'
    params
  end

控制台输出:

2.1.5 :021 > params = [:region, :name, :contact_details, :province_id, :status_id, :start_date]
 => [:region, :name, :contact_details, :province_id, :status_id, :start_date] 
2.1.5 :022 > params.delete(:region)
 => :region 
2.1.5 :023 > params
 => [:name, :contact_details, :province_id, :status_id, :start_date] 

答案 1 :(得分:1)

如果您按如下方式重构代码该怎么办:

 permit_params do
    regular_params = [:name, :contact_details, :province_id, :status_id, :start_date]
    update_params = regular_params + [:region]
    permitted = params[:action] == "update" ? update_params : regular_params
    permitted
  end

答案 2 :(得分:0)

尝试这种方式,也许你的问题不在于许可证参数

  permit_params :name, :contact_details, :province_id, :status_id, :start_date
  # it does not work as you want but maybe can help you find bug