0

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.

  • You need an ActiveRecord Relation to use `update_all`. How are you getting your `my_objcts_arr`? – AbM Oct 10 '16 at 02:04

1 Answers1

0

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"]
foo 
// => [{:a=>"C", :b=>"b"}, {:a=>"C", :b=>"B"}]
Community
  • 1
  • 1
bambery
  • 310
  • 2
  • 5