I’m trying to manage an ActiveRecord model via its priority:integer column. I would like to manage the rows with after_update and after_create hooks to keep their order neat and clean.
I have two needs:
-
Take a current list of items and update their priority attribute to follow strict order.
Example: a list of three items with said priority column.[a.priority = 4, b.priority = 66, c.priority = 92]becomes
[a.priority = 1, b.priority = 2, c.priority = 3] -
Update all rows’ priority to reflect the addition of a new row in the middel of the list.
[a.priority = 1, b.priority = 2, c.priority = 3, d.priority = 4]with an addition of
e.priority = 2create a new list of[a.priority = 1, e.priority = 2, b.priority = 3, c.priority = 4, d.priority = 5]
github repo: https://github.com/digitalcake/priority_manager
For the first case, you could do something like
And the second one
That said, if you are only interested in the ordering and not the absolute position on the list it would be more efficient if instead of using integers to store your priorities, you used floats. Insert a row by assigning a it value between the priorities of the objects you want it to be in between. IE to insert a between b and c with respective priorities pb and pc assign it a priority of pa = (pc + pb) / 2
This way the overall ordering remains intact, but you dont need to touch and resave every object with a higher priority every time you insert a new row.