Mike Mike - 1 year ago 73
Ruby Question

How do I mass update a field for models in an array?

I’m using Rails 4.2.7. How do I mass update a field of an array of my models without actually saving that information to the database? I tried

my_objcts_arr.update_all(my_object: my_object)

but this results in the error

NoMethodError: undefined method `update_all' for #<Array:0x007f80a81cae50>

I realize I could iteraet over the array and update each object individually, but I figure there's a slicker, one-line way in Ruby taht I'm not aware of.

Answer Source

update_all needs to be called on a class level active record model/relation, ie User or TaxReturn. Here is one somewhat related SO post showing some examples, and here is the api doc for update_all. It will send the UPDATE directly to the db (it is an active record method, after all), so it is not what you want.

You're best off iterating and updating the value yourself with collect or something similar, which is only one line.

foo = [{:a=>"a", :b=>"b"}, {:a=>"A", :b=>"B:}] 
// => [{:a=>"a", :b=>"b"}, {:a=>"A", :b=>"B"}]
foo.collect{|x| x[:a]="C"} 
// => ["C", "C"]
// => [{:a=>"C", :b=>"b"}, {:a=>"C", :b=>"B"}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download