我这样使用acts_as_list v0.9.17:
class ListItem < ActiveRecord::Base
acts_as_list scope: [:column1_id, :column2_id], :add_new_at => :bottom
end
当创建一个新的(范围)@list_item
时,比如column1_id
是1
的那个,column2_id
是11
而column3_id
是37
,数据库看起来如下,正如预期的那样:
id | position | column1_id | column2_id | column3_id
--- | -------- | ---------- | ---------- | ----------
750 | 1 | 1 | 11 | 89
751 | 2 | 1 | 11 | 56
752 | 3 | 1 | 11 | 105
753 | 4 | 1 | 11 | 25
754 | 5 | 1 | 11 | 37
然而,当@list_item
被摧毁时,比如说column1_id
是1
,column2_id
是11
而column3_id
是56
(记录id 751
),那么数据库看起来如下:
id | position | column1_id | column2_id | column3_id
--- | -------- | ---------- | ---------- | ----------
750 | 1 | 1 | 11 | 89
752 | 3 | 1 | 11 | 105
753 | 4 | 1 | 11 | 25
754 | 5 | 1 | 11 | 37
这意味着position
2
存在差距。
如何预防或调整差距?也就是说,当列表项被销毁时,如何处理列表项的重新排序?
注意:我知道有methods that change position and reorder list,但我不知道是否以及如何使用它们来解决问题(也许使用某些remove_from_list
)。
正如您所说,您需要使用您提供的方法,您可以在控制器或模型本身中执行此操作。如果你是那种喜欢回调的人,那么:
class ListItem < ActiveRecord::Base
acts_as_list scope: [:column1_id, :column2_id], :add_new_at => :bottom
before_destroy { |record| record.remove_from_list }
....
end
有些人不喜欢像处理回调那样处理逻辑,所以你也可以直接将它添加到你的控制器中:
class ListItemsController < Wherever
....
....
def destroy
@list_item.remove_from_list
@list_item.delete
....
end
end
我个人将它添加到模型中,但它们都做同样的事情。
如果您需要尝试修复其中缺少记录的列表,请假设您的LineItems的ID和位置为0-4和6-9,缺少位置5.您可以在控制台中使用以下命令进行脏乱修复:
LineItem.where('position >= ?', 5).each { |line_item| line_item.update_attributes(position: line_item.position - 1) }
这将找到位置超过4的所有LineItem,并将每个LineItem减少一个,从而为您提供0-8的正确排序列表。