Reputation: 486
I have an ActiveRecord Model called Animal. Animal has id and client_id. In my app have an array called @selectedanimals that contains the id's of the animals I want to update such as: @selectedanimals: ["6", "14", "5"]. I have the value of a new client_id for these animals like @newclient.id and I want to update all of these Animal records with the new client_id. What I have now is:
Animal.update_all({:client_id => @transferclient.id}, {:id => @selecteanimals})
I know this is not 100% correct because it is having a problem with :id. I get an error like this: Called id for nil, which would mistakenly be 8 -- if you really wanted the id of nil, use object_id
Forgive my ignorance but this is my first time using update_all and I don't see any examples where you pass it an array of the ids of the records you want to update so any help would be appreciated much.
EDIT: Apparently the @transferclient.id was not properly defined. That was my problem. Thanks all.
Upvotes: 2
Views: 7997
Reputation: 1452
I am new to Ruby so I don't know if there's been some recent change in the API but Danpe's answer as well as the initial suggestion that actually worked according to the asker, didn't work for me. They both raised a syntax error.
The solution that worked for me and is actually proposed in the API documentation is this:
Animal.where(:id => @selectedanimals).update_all(:client_id => @transferclient.id)
Upvotes: 2
Reputation: 19057
You need to check if id is inside that array:
Animal.update_all({:client_id => @transferclient.id}, {"id IN (?)" , @selecteanimals})
Upvotes: 0