2

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.

4
  • Are you trying to update with single client_id or multiple client_id's ? Commented Oct 22, 2013 at 6:25
  • single client_id and multiple animals - but, I found that the real issue with the code was that @transferclient.id was not properly defined. Commented Oct 23, 2013 at 13:55
  • Does @Danpe's answer work ? Commented Oct 23, 2013 at 14:01
  • It might work but the code I have listed in my question worked just fine once I properly defined @transferclient.id. Commented Oct 23, 2013 at 14:53

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You need to check if id is inside that array:

Animal.update_all({:client_id => @transferclient.id}, {"id IN (?)" , @selecteanimals})

1 Comment

Thanks for your answer but the code I had in my question worked once I properly defined @transferclient.id. That was my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.