在更新期间在模型上排序位置

时间:2012-02-28 21:44:12

标签: ruby-on-rails ruby ruby-on-rails-3 acts-as-list

我在我的产品型号上使用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,当它应该返回具有旧产品位置的产品时。

感谢您的帮助,如果我走在正确的轨道上或者有更简单的方法,请告诉我。

1 个答案:

答案 0 :(得分:2)

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

@product.insert_at(1)

尝试而不是手动更改位置,看看是否不会简化您的代码。