我在rails中有一个带有以下列的清单模型。
product_id:int | content:string | archived:boolean | done:boolean
我目前正在列出那些通常像
的视图中的清单<ul>
<%= @checklists.each do |list| %>
<li><%= list.content %></li>
<% end %>
</ul>
现在我想让用户重新排列清单,例如todoist。
我怎么能在铁轨上做到这一点?我是否必须使用order:int
等其他列进行数据库迁移?
答案 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)) }