ruby-on-railsactiverecordrails-cells

How to persist the arrangement of cells with ActiveRecord


I'm building a Rails application with a dashboard composed of a sorted collection of cells. The ultimate goal is to allow the user to arrange the cells and have that persisted to the database, but I'm unable to fathom the architecture required to make this happen.

I'm less concerned about the UI/UX of dragging and dropping cells, and more concerned about the models required to represent this in a SQL database with ActiveRecord.

Any help would be appreciated. Thanks!


Solution

  • This is a pretty solved problem, there are numerous gems that will handle this for you.

    Typically you'd add a "position" integer column to the table, and sort by that when you select records. When you want to move an item A to a new position after item B, you first add 1 the position of all records that are sorted after B to make a new space for A, and then to set A's position to B.position + 1. This way, sorting involves only two writes.