Sylar Sylar - 5 months ago 8
Ruby Question

Update Each Array-Object Value in Rails

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


Old object would be like:

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

]


New should be like:

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

]


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.

Is the title name correct?

Answer

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

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.

So let's assume

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])}

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

Comments