Praveen KJ
Praveen KJ

Reputation: 650

Rails rearranging orders in checklist model

I am having a checklist model in rails with following columns.

product_id:int | content:string | archived:boolean | done:boolean

and i am currently listing those checklists in views normally like

<ul>
    <%=  @checklists.each do |list| %>
       <li><%= list.content %></li>
    <% end %>
</ul>

Now i want to let users rearrange checklists orders like in todoist.

How can i do that in rails? Do i have to do a migration to the database with additional columns like order:int?

Upvotes: 1

Views: 40

Answers (1)

Alexander Sysuiev
Alexander Sysuiev

Reputation: 721

Well, you can try add additional field like list_index Then in before create callback in the model you can:

def set_index
  list_index = self.class.last_index + 1
end

def self.last_index
  self.order(list_index: :desc).first.list_index
end

Then on change position:

def change(current_index)
  self.class.where(self.class.arel_table[:list_index].gte(current_index)).update_all('list_index = list_index + 1')
  self.update(list_index: current_index)
end

You can move the selection of elements with a higher index to the scope:

scope :after_index, ->(current_index) { where(self.arel_table[:list_index].gte(current_index)) }

Upvotes: 1

Related Questions