私の製品モデルでacts_as_listを使用しており、手動で位置を編集できるようにしようとしています。私は位置1に位置3から製品3を編集した場合、現在、それは他の製品更新中のモデルの注文位置
例を調整しません:位置1に位置3から移動製品
ID名位置
1製品1
2製品2
3製品3
は
ID名位置
になります1製品1
2製品2
3製品1
しかし、私はそれが2
2製品3
3製品1
製品1 ID名位置
に帰着する必要が
私は結論に達しました私のコードを私の製品アップデートクラスに加えるべきです。ここで私はこれまで持っているものです: 私はそれらのすべての位置が、私のコードをインクリメントし、その後、すべての古い製品の範囲をwithing製品と新製品をつかむしようとしている。このコードでは
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の位置を5に変更するとソートされません。何か案は? – ruevaughn
私はacts_as_listを自分でしばらく使っていませんが、最低位よりも低い数字を移動すると、あなたが望むポジションが当然となりますので、3つのアイテムしか持たない場合は5、それは1、2、5を持っています。これは本当に内部リストの表現については問題ではありません - Product.find_by_position(2).lower_itemを使用する場合、私はまだ下部項目を正しく見つけるはずです。おもう。 – Veraticus
私は、番号を最も低い数字の位置に移動しようとしていて、それよりも低くない場合はどうなりますか?今のところ、それは先に進んで番号を割り当て、残りの数字を増やさないように見えるので、私はポジション1に2つの数字がついているでしょうか? – ruevaughn