2

製品モデルでacts_as_listを使用しており、手動で位置を編集できるように作成しようとしています。現在、製品3を位置3から位置1に編集すると、他の製品は調整されません。

例:製品を位置3から位置1に移動します

ID名ポジション
1製品12製品23
製品
3

結果は

ID名前位置
1製品12製品23
製品
1

しかし、私はそれが結果として必要です

ID名前位置
1製品22製品
33
製品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を返し続けます。

助けてくれてありがとう、そして私が正しい軌道に乗っているかどうか、またはこれを行うより簡単な方法があるかどうか私に知らせてください。

4

1 に答える 1

3

act_as_listは、独自のコードを追加する必要なく、この種のことを行うためのヘルパー メソッドを提供します。商品を 3 位から 1 位に移動し、他のすべてを自動的に再注文する場合は、次のようにします。

@product.insert_at(1)

位置を手動で変更する代わりにそれを試して、コードが単純化されないかどうかを確認してください。

于 2012-02-28T21:54:22.710 に答える