-1

I have an array of objects in Rails for some table. I want to update its order field by the position of that object in the array with a single Active Record Query. How can I do that?

I have tried the update_all.(:"order" => ?) but couldn't get the object which is updating in update_all.

petezurich
  • 9,280
  • 9
  • 43
  • 57
vishesh268
  • 123
  • 1
  • 1
  • 9

2 Answers2

1

Suppose @user (only a reference you can use your corresponding object) is the array of objects (Activerecord) , then to update order field of all users in the array, you would have to run the following query

@user.update_all(order_field: value)
Rohan
  • 2,681
  • 1
  • 12
  • 18
0

Suppose you have an array of posts, then you can do something like the following

posts.each_with_index do |post, index| 
  post.update_attributes order: index 
end 

This will execute a single query for each post. If you want a single query to update all the posts in the array, that is a lot harder to achieve. Options I can think of:

  • bulk updating
  • using a stored procedure
nathanvda
  • 49,707
  • 13
  • 117
  • 139
  • its correct but , I am trying to do it in a single query is it possible...?? – vishesh268 Apr 12 '18 at 09:51
  • It is possible, but a lot more complicated and not sure it is worth it imho. Check this answer: https://stackoverflow.com/questions/11563869/update-multiple-rows-with-different-values-in-a-single-sql-query – nathanvda Apr 12 '18 at 10:39