[英]Rails multiple record update
The following array of boolean attributes for multiple records以下多条记录的布尔属性数组
{"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"}
is being posted from one controller to a child controller with the following action that has un-conventional naming for the parameters.正在通过以下操作从一个控制器发布到子控制器,该操作具有非常规的参数命名。
def update_all
params[:ts].keys.each do |id|
@daystruttimeslot = Daystruttimeslot.find(id.to_i)
@daystruttimeslot.update(ts_params)
end
end
is hitting the error 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
undefined local variable or method 'ts_params' for #<DaystruttimeslotsController:0x00007fa118f262f8> Did you mean? to_param params @_params
How can these parameters be properly processed by this action?这个动作如何正确处理这些参数?
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
This does a single read operation instead of fetching each record separately and also provides a ivar that actually makes sense instead of whatever is at the end of the loop.这会执行单个读取操作,而不是分别获取每条记录,并且还提供了一个实际有意义的 ivar,而不是循环末尾的任何内容。
If you need to validate that all the ids are correct compare ts.keys.length
to @daystruttimeslots.size
.如果您需要验证所有 id 是否正确,
ts.keys.length
与@daystruttimeslots.size
进行比较。 You also might want to consider wrapping this in a transaction so that the changes are rolled back if any of the updates fail instead of just leaving the job half done.您可能还想考虑将其包装在一个事务中,以便在任何更新失败时回滚更改,而不是让工作完成一半。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.