【问题标题】:Rails ActiveModel::ForbiddenAttributesError Editing multiple recordsRails ActiveModel::ForbiddenAttributesError Editing multiple records
【发布时间】:2014-11-06 23:49:56
【问题描述】:

我按照 Railscast 第 165 集(修订版)介绍了如何以一种形式编辑和更新多条记录。但是当我提交表单以同时编辑多条记录时,我得到:

ActiveModel::ForbiddenAttributesError

对于这一行:

product.update_attributes(params[:product].reject { |k,v| v.blank? })

参数:

参数:

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"g5C2siF5GcWfPxhph4utWn8JBs2JXEpIUBDO6OlFyQQ=",
 "product_ids"=>["11142",
 "11143"],
 "product"=>{"user_id"=>"",
 "allow_multi_users"=>"true",
 "state_id"=>"",
 "site"=>"",
 "department"=>"",
 "room"=>"",
 "asset_type_id"=>"",
 "asset_model_id"=>"",
 "sync_with_jss"=>"",
 "carrier_id"=>"",
 "mobile_contract_req_date"=>"",
 "mobile_contract_end_date"=>"",
 "mobile_international_plan"=>"",
 "mobile_tethering"=>"",
 "mobile_account"=>""},
 "commit"=>"Update"}`

通常,我认为这是因为我不允许强参数中的属性。但这不是一个属性,它是包含所有值的表单的参数。

这是针对我的 Products.rb 模型的,所以它不应该已经接受 params[:product] 吗?

products_controller.rb

private  
  def product_params
    params.require(:product).permit(:mobile_account, :mobile_international_plan, :mobile_tethering, :mobile_contract_end_date.. )
  end

使用 Rails 4.0.0

【问题讨论】:

  • 请尝试将puts params[:product] 的值添加到您的问题中。
  • 我在错误期间添加了参数输出。

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


【解决方案1】:

试试这个

def update
  ...
  product.update_attributes(product_params)
  ...
end

private

  def product_params
    params.require(:product).permit(:mobile_account, :mobile_international_plan, :mobile_tethering, :mobile_contract_end_date.. )
  end

字段列表是您希望用户发送更新或创建的字段。

您可以找到更多信息here

当您尝试使用具有不允许的参数的 params 对象更新模型时,会引发错误 ActiveModel::ForbiddenAttributesError,必须允许表单中存在的所有字段来更新记录。

【讨论】:

  • 那你必须用 product_params 调用 update_attributes
  • 哇。当然!这是完全有道理的,我没有看到它。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 2013-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多