我一直在寻找一天半的解决方案。
我有几个表(类别),允许用户拖放每一行(项目)以重新排序每个项目在该表(类别)上的位置。我正在使用SortableJS来处理拖放,并且我拥有它以便在同一类别中重新排序工作。
在我的后端,我有一个使用 Jbuilder 返回 JSON 的 Rails API,并且正在使用acts_as_list gem来处理我的位置。
当我将项目从类别 A 拖到类别 B 时,我在弄清楚如何处理重新排序时遇到问题。我认为问题在于控制器操作以及我无法提出解决方案来接收多个类别的更新,并且然后使用 Jbuilder 返回更新后的类别的位置。一些帮助将不胜感激!
项目列表.vue
<script>
methods: {
async dragReorder({ item, to, from, oldIndex, newIndex, oldDraggableIndex, newDraggableIndex, clone, pullMode }) {
// item that was dragged
const draggedItem = JSON.parse(item.getAttribute('data-item'));
// initial payload
const payload = {
category_id: draggedItem.category_id,
category_item_id: draggedItem.pivot.id,
item_id: draggedItem.id,
new_index: newIndex + 1,
user_id: this.user.id,
};
const newCategory = JSON.parse(to.getAttribute('data-category'));
// if item is dragged to new category
if (pullMode) payload.new_category_id = newCategory;
await categoryService.updatePosition(payload);
},
},
mounted() {
this.$nextTick(() => {
const tables = document.querySelectorAll('.items-table-container');
tables.forEach(table => {
const el = table.getElementsByTagName('tbody')[0];
Sortable.create(el, {
animation: 150,
direction: 'vertical',
easing: 'cubic-bezier(.17,.67,.83,.67)',
group: 'items-table-container',
onEnd: this.dragReorder,
});
});
})
},
</script>
类别.rb
class Category < ApplicationRecord
has_many :categories_items, -> { order(position: :asc) }
has_many :items, through: :categories_items, source: :item
accepts_nested_attributes_for :items
end
categories_item.rb
class CategoriesItem < ApplicationRecord
belongs_to :category
belongs_to :item
acts_as_list scope: :category
end
项目.rb
class Item < ApplicationRecord
has_many :categories_items
has_many :categories, through: :categories_items, source: :category
end
类别控制器.rb
def update_position
item = CategoriesItem.find_by(category: params[:category_id], item: params[:item_id])
# if item was moved to new category
categories = []
if params[:new_category_id]
item.update(category_id: params[:new_category_id])
Item.find(params[:item_id]).update(category_id: params[:new_category_id])
item.insert_at(params[:new_index]) unless !item
categories << Category.find(params[:category_id])
categories << Category.find(params[:new_category_id])
else
item.insert_at(params[:new_index]) unless !item
categories << Category.find(params[:category_id])
end
@categories = categories
end
update_position.json.jbuilder
json.array! @categories do |category|
json.(category, :id, :name, :created_at, :updated_at)
json.categories_items category.categories_items do |category_item|
json.(category_item, :id, :category_id, :item_id, :created_at, :updated_at, :position)
end
end