繁体   English   中英

Rails 多记录更新

[英]Rails multiple record update

以下多条记录的布尔属性数组

{"utf8"=>"✓","_method"=>"patch", "authenticity_token"=>"...",
 "ts"=>
  {"1"=>{"go"=>"0", "pickup"=>"0", "delivery"=>"1"},
   "2"=>{"go"=>"0", "pickup"=>"0", "delivery"=>"1"},
   "3"=>{"go"=>"0", "pickup"=>"0", "delivery"=>"1"},
   [...]},
 "commit"=>"Save changes"}

正在通过以下操作从一个控制器发布到子控制器,该操作具有非常规的参数命名。

   def update_all
      params[:ts].keys.each do |id|
        @daystruttimeslot = Daystruttimeslot.find(id.to_i)
        @daystruttimeslot.update(ts_params)
      end
    end

正在undefined local variable or method 'ts_params' for #<DaystruttimeslotsController:0x00007fa118f262f8> Did you mean? to_param params @_params遇到错误undefined local variable or method 'ts_params' for #<DaystruttimeslotsController:0x00007fa118f262f8> Did you mean? to_param params @_params undefined local variable or method 'ts_params' for #<DaystruttimeslotsController:0x00007fa118f262f8> Did you mean? to_param params @_params

这个动作如何正确处理这些参数?

def update_all
  ts = params.require(:ts)
  @daystruttimeslots = Daystruttimeslot.where(id: ts.keys)
  @daystruttimeslots.each do |d|
    d.update(ts.fetch(d.id.to_s).permit(:go, :pickup, :delivery))
  end
end

这会执行单个读取操作,而不是分别获取每条记录,并且还提供了一个实际有意义的 ivar,而不是循环末尾的任何内容。

如果您需要验证所有 id 是否正确, ts.keys.length@daystruttimeslots.size进行比较。 您可能还想考虑将其包装在一个事务中,以便在任何更新失败时回滚更改,而不是让工作完成一半。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM