Ruby on rails 更新期间模型上的订购位置

Ruby on rails 更新期间模型上的订购位置,ruby-on-rails,ruby,ruby-on-rails-3,acts-as-list,Ruby On Rails,Ruby,Ruby On Rails 3,Acts As List,我正在我的产品模型上使用acts_as_列表,并尝试将其设置为您可以手动编辑位置。当前,如果我将产品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,

我正在我的产品模型上使用acts_as_列表,并尝试将其设置为您可以手动编辑位置。当前,如果我将产品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
def更新
#要手动编辑acts_as_列表,只需获取位置较高的所有项目
#大于当前项,并增加每个项。
#查找要更改的产品
@product=product.find(参数[:id])
#查找是否有产品已位于请求的位置
旧产品=产品。按位置和类别id查找(参数[:位置],参数[:类别id])
#如果旧产品的位置小于当前产品,则返回介于-1之间的产品
如果@product.position>old_product.position
产品=产品。其中(:Product<@Product.position,:Product>@old_Product.position)
产品。每个do |产品|
产品.职位+1
结束
#如果旧产品位置大于当前产品位置,则返回介于两者之间的产品并减少所有位置
elsif old_product.position<@product.position
products=Product.all
产品。每个do |产品|
product.position=product.position-1
结束
结束
在这段代码中,我试图获取旧产品和新产品范围内的所有产品,然后增加所有产品的位置,但我的代码不起作用,似乎调用old_product=product。按位置查找,类别id(params[:position],params[:category_id])不断返回零,何时应将产品与旧产品的位置一起退回

感谢您提供的帮助,并让我知道我是否在正确的轨道上,或者是否有更简单的方法来执行此操作。

提供了帮助器方法来执行此类操作,而无需添加您自己的代码。如果您想将产品从位置3移动到位置1,并自动重新订购其他所有产品,请执行以下操作:

@product.insert_at(1)

试着这样做,而不是手动改变位置,看看这是否能简化您的代码。

哇,感谢这帮了大忙,我不知道为什么我在前面的代码中没有看到这一点。当我将它添加到较低的位置时,它似乎起作用,但当我将1的位置更改为5时,它不会排序。有什么想法吗?我已经有一段时间没有使用acts_as_list了,但我认为如果你移动的数字低于最低位置,这是理所当然的,这是你想要的位置——所以如果你只有三个项目,并且在5处插入其中一个,那么它将有1,2,5。但是,这对于内部列表表示并不重要——如果您使用Product.find\u by\u position(2)。lower\u item,我认为它仍然应该正确地找到lower item。我想,若我试着把一个数字移到最低的位置,而不是再低一点呢?到目前为止,它似乎只会将数字分配到最低的位置,而不会增加其他数字,因此我将在位置1中保留两个数字?如果要将数字移动到最低的位置,请尝试
@product。移动到底部
。酷,我将创建一个If语句来检查它是否是最低的,如果是的话,把你移到底部,对吗?