パラメーターとして渡された投稿 ID を受け取り、それらを公開する前に特定の順序に並べ替えるコントローラー アクションの作成に問題があります。
投稿にはposition
属性があり (私はソートに act_as_list を使用しています)、公開または非公開のいずれかです (named_scopesPost.published
およびPost.unpublished
で検索可能)。
基本的に、ユーザーが未公開の投稿をキューにドラッグし、ID をpost_ids
パラメーターとして次のようなコントローラー メソッドに渡すことで公開できるようにする JavaScript インターフェースがあります。
def publish
Post.update_all(['published=?', true], :id => params[:post_ids])
redirect_to admin_path
end
このような投稿を公開するとうまくいきます。次に行う必要があるのは、特定の順序で投稿をその位置で並べ替えることです。ここで問題が発生します。
ユーザーが投稿 5、投稿 3、投稿 7 をキューにドラッグし、[公開] をクリックしたとします。
私がやりたいことは、すべての Post を整理して、最初の位置に 5、3、7 を順番に配置し、残りの Post オブジェクトを既にあった順序で配置することです。つまり、Post.position でソートすると、[5, 3, 7, ...the rest of the posts in order here...]
次に、ユーザーが 2 つの新しい投稿をキューにドラッグして [公開] をクリックした場合 (今回は投稿 2 と 4 としましょう)、投稿は順番どおりに表示されます。[2, 4, 5, 3, 7, ...the rest of the posts in order here...]
最後の例として、ユーザーが投稿 10、1、および 12 をキューに移動して公開するとします。順序は次のようになり[10, 1, 12, 2, 4, 5, 3, 7, ...the rest of the posts in order here...]
ます。
私が取り組んでいるコードを示しますが、正しくソートされていないため、役立つかどうかはわかりません. しかし、本質的には、これは 2 つの配列を取る問題だと思います。1 つ目はすべての Posts で、2 つ目は公開する Posts であり、Posts to publish 配列の各項目をすべての Posts 配列の先頭に配置してから公開します。私はそれを機能させることができないようです。ここで何か助けていただければ幸いです。お時間をいただきありがとうございます。
編集 参考 までに、これまでに書いたコードを次に示します。テストでは、このメソッドは最初はキューから投稿を正しく並べ替えているように見えますが、公開された後続の投稿は、公開された投稿リストの先頭に移動しません。
def publish
if params[:to_publish].present?
# :to_publish are the posts dragged into the queue in order.
# Here I'm cleaning up the Javascript input and then iterating
# through them to update their sort order.
params[:to_publish].to_s.split(",").uniq!.each_with_index do |id, index|
Post.update_all(['position=?', index + 1], ['id=?', id])
end
end
# :post_ids are the posts to be published, order is irrelevant.
# For client-side reasons they're passed as a separate parameter.
Post.update_all(['published=?', true], :id => params[:post_ids])
redirect_to admin_path
end