rails4 多条记录更新

rails4 multiple record updating

以下控制器操作在 rails 4.2 下失败,但在 rails 3.2

中运行
params[:inventoris_for_product].each do |id, inventori_params|
  @inventori = Inventori.find(id)
  @inventori.update_attributes(inventori_params)
end

即使私有方法启用强参数

def inventori_params
  params.require(:inventori).permit(:product_id, ...)
end

ActiveModel returns ForbiddenAttributesError

提交的参数格式为Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "inventoris_for_product"=>{"2140"=>{"quantity"=>"4", "price_1"=>"45.0" [...]

可以覆盖,

params[:inventoris_for_product].each do |id, attrs|
  @inventori = Inventori.find(id)
  unlocked_attrs = ActiveSupport::HashWithIndifferentAccess.new(attrs)
  @inventori.update_attributes(unlocked_attrs)
end

但不需要。

新句法方法缺少什么?

如果你想更新多条记录,你可以试试link这个:

Inventori.where(id: [1, 2, ...]).update_all(attr_name: val)

设置控制器动作

@inventori.update attrs.permit(:quantity, :price_1[...])

成功了