製品モデルで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を返し続けます。
助けてくれてありがとう、そして私が正しい軌道に乗っているかどうか、またはこれを行うより簡単な方法があるかどうか私に知らせてください。