Search code examples
ruby-on-railspostgresqltodomvc

How to implement saving of order of todos / list?


I am developing an application which is very similar to todo list in its nature, except order of todos matters and can be changed by user.

What's a good way to save this order in db without having to re-save whole todo list upon change of order?

I am developing in Rails, Postgres and React, newest versions.

I am thinking to save it as an array in User Todos (there can be multiple users of the application), but I am thinking it could complicate things a little as every time I create a todo I would have to save the List also.


Solution

  • You can look into acts_as_list gem and for this you'll have to add an additional column position in your table. But this will do mass update on the records. But this gem is frequently updated.

    If you want an optimised solution and minimise the number of updates on changing the list then you should check ranked_model gem but this one is not frequently updated. There is a brief on how it works :-

    This library is written using ARel from the ground-up. This leaves the code much cleaner than many implementations. ranked-model is also optimized to write to the database as little as possible: ranks are stored as a number between -2147483648 and 2147483647 (the INT range in MySQL). When an item is given a new position, it assigns itself a rank number between two neighbors. This allows several movements of items before no digits are available between two neighbors. When this occurs, ranked-model will try to shift other records out of the way. If items can't be easily shifted anymore, it will rebalance the distribution of rank numbers across all members of the ranked group.

    You can refer this gem and make your own implementation as it only supports rails 3 & 4.