DEV Community


Posted on

Using acts_as_list for easy ordering of items


acts as list is a ruby gem designed for easy ordering and reordering of object contained in a list. I have recently become a little familiar with this gem while working on a project management board application.

Set up

This tutorial/guide assumes you already know some basics of using ruby on rails like setting up a database, creating migrations and resources, etc..

The first thing that needs to be done is installing the gem. This can be done by adding gem acts_as_list to your gemfile within your RoR application and running bundle in the command line.

Once finished with the installation, you are going to need a special column of "position" on any resource you want to be organized like a list. If you are creating a resource from scratch, be sure to have a column called position that takes in an integer datatype. To add this to existing resources, create a new migration for adding this column to a resource and run the migration(this code from the official docs):

rails g migration AddPositionToTodoItem position:integer
rake db:migrate
Enter fullscreen mode Exit fullscreen mode

After adding this column to a resource, you then need to go into the model for that resource and add the acts_as_list method inside the model. You can also set the scope of this method to relate to another resource. Here is an example from my code:

class Card < ApplicationRecord
  acts_as_list scope: :list
  belongs_to :list

class List < ApplicationRecord
     acts_as_list scope: :project_id
     has_many :cards, ->{ order(position: :asc) }, dependent: :destroy
Enter fullscreen mode Exit fullscreen mode

Here I have set up a has_many -> belongs_to relationship with Cards and Lists. I then have the scope of acts_as_list set to the lists so the position of the cards is tracked only within a single list.

After this, you're pretty much good to start creating instances of your resources and using other methods that come with this gem. Keeping with the example I have, if I create a new card with a reference to a list, the position column is populated automatically starting with position of "1". If I create more cards with the same list as reference, it will increment the position for each card on its own.

Once you have a few things with their position created, you can use various methods to change/ manipulate the position. Here is a list of methods from the documentation:

Image description

If you use move_higher on an Object, it will decrease its position(moving it higher in the list) and will subsequently move all others it moved above lower (increasing their position in response). This makes it effortless to update your lists order server-side, as well as display information about your lists to the user with the attribute returning methods.

Hopefully you find this useful, there are a ton of possibilities with this simple but powerful gem.


Top comments (0)