我在我的产品模型上使用acts_as_list,并尝试制作它,以便您可以手动编辑位置。目前,如果我将产品 3 从位置 3 编辑到位置 1,它不会调整其他产品
示例:将产品从位置 3 移动到位置 1
ID 名称 位置
1 产品 1
2 产品 2
3 产品 3
将导致
ID 名称 职位
1 产品 1
2 产品 2
3 产品 1
但我需要它来
ID 名称 职位
1 产品 2
2 产品 3
3 产品 1
我得出的结论是我应该将代码添加到我的产品更新类中。这是我到目前为止所拥有的:
def update
#To edit acts_as_list manually, just get all items with a position higher
#than the current item and increment each one.
#Find the product to be changed
@product = Product.find(params[:id])
#Find if there is a product already in the requested position
old_product = Product.find_by_position_and_category_id(params[:position], params[:category_id])
#If the old product has a position less then the current product, return the products in between minus 1
if @product.position > old_product.position
products = Product.where(:product < @product.position, :product > @old_product.position)
products.each do |product|
product.position + 1
end
#If old product position is greater then current product position, return the products in between and decrement all position
elsif old_product.position < @product.position
products = Product.all
products.each do |product|
product.position = product.position - 1
end
end
在这段代码中,我试图获取旧产品和新产品范围内的所有产品,然后增加所有产品的位置,但我的代码不起作用,似乎调用 old_product = Product.find_by_position_and_category_id (params[:position], params[:category_id]) 一直返回 nil,当它应该返回具有旧产品位置的产品时。
感谢您的帮助,如果我走在正确的轨道上,或者是否有更简单的方法,请告诉我。