Updating records ordinal value based on Sortable array order

I’ve implemented the Sortable.js in my view to sort some list elements. After sort the list is correctly updated in the db based on the layout in the browser.

def update_array_order(ids)
  self.object_assets.update_all(['ordinal = FIND_IN_SET(id, ?)', ids.join(',')])

Fine. The above method get passed an JS array of integers(ids). I’m not including JS or controller code because I don’t feel it’s important.

However my lists are paginated and if you aren’t viewing the complete list at time of sort, the records that aren’t present get converted to 0 in the db. I would like it to leave the ids that aren’t present alone (as it wouldn’t screw up the overall ordering). With Rails 4 they’ve taken the condition out of update_all, so I need to create a where clause, so I repeated the FIND_IN_SET with a != NULL… It’s not working.

Wondering if anyone has had the need for a condition with update_all while using Rails 4 and what you did.


In the event anyone else has this issue, here’s the solution I came up with. FIND_IN_SET returns 0 (no null) if not found. Tack on a where right after your association testing to see if it’s greater than 0

.where(['FIND_IN_SET(id, ?) > 0', ids.join(',')])

and voila!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.