更新Rails中的每个数组对象值 [英] Update Each Array-Object Value in Rails

查看:64
本文介绍了更新Rails中的每个数组对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想为Rails 5中的模型更新每个表列.

Basically I want to update each table column for a Model in Rails 5.

str = "abc---def"

str.split('---').map do |a|
 Foo.where(product_id:1).update_all(bar: a)
end

旧对象将是:

[
 [0] { product_id: 1,
       ...,
       bar: "xxx",
       ...
     },
 [1] { product_id: 1,
       ...,
       bar: "xxx",
       ...
     }

]

新功能应为:

[
 [0] { product_id: 1,
       ...,
       bar: "abc",
       ...
     },
 [1] { product_id: 1,
       ...,
       bar: "def",
       ...
     }

]

但是我得到的每个都是bar: "def". Rails中有一种干净的方法可以实现我想要的吗? update_attributes给出错误.

But what I got is bar: "def" for each. Is there a clean method in rails to achieve what I want? update_attributes gives an error.

标题名称正确吗?

推荐答案

首先让我们从一些基础知识开始.

First of all let's get started from some basics.

您要更新多行,并希望为每行设置不同的值.因此,无法像您一样在单个查询中完成.因此,您需要遍历Foo对象并分别设置每个对象.

You want to update multiple rows and want to set different value for each row. So it cannot be done in single query like you are doing. So you need to loop through the Foo objects and set each one separately.

让我们假设

str = "abc---def---ghi---jkl"
tokens = str.split('---') 
foos_to_update = Foo.where(product_id: 1) #Let's assume it will return 4 or lesser records. (otherwise you need to tell what do you wanna do if it returns more then `tokens`)
foos_to_update.each_with_index {|foo,i| foo.update(bar: tokens[i])}

最后一行是循环遍历返回的对象并为每个对象设置bar值.

The last line is looping through returned objects and setting the bar value for each object.

这篇关于更新Rails中的每个数组对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆