Rails在清单模型中重新排列订单

时间:2018-05-02 08:45:53

标签: ruby-on-rails ruby postgresql

我在rails中有一个带有以下列的清单模型。

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

我目前正在列出那些通常像

的视图中的清单
<ul>
    <%=  @checklists.each do |list| %>
       <li><%= list.content %></li>
    <% end %>
</ul>

现在我想让用户重新排列清单,例如todoist

我怎么能在铁轨上做到这一点?我是否必须使用order:int等其他列进行数据库迁移?

1 个答案:

答案 0 :(得分:1)

好吧,您可以尝试添加其他字段,例如list_index 然后在模型的before create回调中,您可以:

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

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

然后改变位置:

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

您可以将具有更高索引的元素选择移动到范围:

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