返回资讯中心
外部精选
软件工程
#开发者实时流

Drag and Drop Reordering in Rails

<p>Every app I worked on has a list that somebody wants in a very specific order. Carousel slides. Menu items. The steps of an onboarding flow. The plans on a pricing page.</p>

Hacker News 最新adrianthedev2026/11/10 · 7 天前30 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

<p>Every app I worked on has a list that somebody wants in a very specific order. Carousel slides. Menu items. The steps of an onboarding flow. The plans on a pricing page.</p> <p>It always starts the same way. "Can I just drag them around?" Sure you can. You add a <code>position</code> column, install <code>acts_as_list</code>, drop in SortableJS and it's working before lunch.</p> <p>I'm saying "working", but what I really mean is "working until the first customer touches it". Because then somebody drags a row and the order is wrong. Not every time. Just sometimes.</p> <p>We do this on our own <a href="https://avohq.io/pricing" target="_blank">pricing page</a>. There are 23 add-ons and 48 plans on it, and we order both by dragging rows in our Avo app. The add-on doing the work is Record Reordering, and it sits at position 22 of 23 (yes, it reorders itself 🫣).</p> <p>If you're in a hurry, here's the gist: an integer <code>position</code> column, <code>acts_as_list</code> scoped to the parent, SortableJS in a Stimulus controller and a <code>PATCH</code> action that calls <code>insert_at</code> inside a lock on the parent.</p> <p>Below I go through that setup, then through the seven things that break once folks start using it, and how to fix each one. Most of the fixes are already inside our add-on, so I'll point you to where.</p> <aside class="takeaways-message"> <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"></path><path d="M9 18h6"></path><path d="M10 22h4"></path></svg> <h2 class="text-lg font-bold">Key Takeaways</h2> <ul> <li><span><strong>Keep the order in an integer <code>position</code> column</strong> and let <code>acts_as_list</code> (or its newer sibling, <code>positioning</code>) shuffle the rows. Backfill it before you ship.</span></li> <li><span><strong>Scope the list</strong> to its parent (<code>acts_as_list scope: :carousel</code>), otherwise dragging a slide in one carousel moves slides in another one.</span></li> <li><span><strong>Send the database position, not the DOM index.</strong> On page 2 the first row is not position 1, so add the first visible record's position to the drop index.</span></li> <li><span><strong>Add a unique index and lock the parent</strong> on every change. Two people dragging at the same time is how you get duplicate positions.</span></li> <li><span><strong>Keep buttons next to the drag handle.</strong> Keyboard users can't drag, and nobody can drag a row to another page.</span></li> </ul> </aside> <h2>The setup</h2> <p>I'll use a <code>Slide</code> that belongs to a <code>Carousel</code>. It's the same shape as menu items in a <a href="https://avohq.io/rails-cms" target="_blank">CMS</a> or tasks in a to-do list.</p> <h3>1. Add a position column and backfill it</h3> <div class="code-highlight code-block-wrapper"> <button type="button" class="code-copy-button" data-controller="clipboard" data-clipboard-success-message-value="Copied!" data-clipboard-error-message-value="Failed to copy!" data-clipboard-text="bin/rails g migration AddPositionToSlides position:integer "> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewbox="0 0 20 20" fill="currentColor" class="copy-icon"> <path d="M6 6V2c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-4v4a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V8c0-1.1.9-2 2-2h4zm2 0h4a2 2 0 0 1 2 2v4h4V2H8v4zM2 8v10h10V8H2z"></path> </svg> </button> <pre class="code-highlight bash"><code>bin/rails g migration AddPositionToSlides position:integer </code></pre> </div><div class="code-highlight code-block-wrapper"> <button type="button" class="code-copy-button" data-controller="clipboard" data-clipboard-success-message-value="Copied!" data-clipboard-error-message-value="Failed to copy!" data-clipboard-text="class AddPositionToSlides &lt; ActiveRecord::Migration[8.1] def change add_column :slides, :position, :integer
reversible do |dir|
  dir.up do
    execute &lt;&lt;~SQL
      UPDATE slides SET position = ranked.rank
      FROM (
        SELECT id, ROW_NUMBER() OVER (PARTITION BY carousel_id ORDER BY created_at, id) AS rank
        FROM slides
      ) AS ranked
      WHERE slides.id = ranked.id
    SQL
  end
end

add_index :slides, [:carousel_id, :position], unique: true

end end "> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewbox="0 0 20 20" fill="currentColor" class="copy-icon"> <path d="M6 6V2c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-4v4a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V8c0-1.1.9-2 2-2h4zm2 0h4a2 2 0 0 1 2 2v4h4V2H8v4zM2 8v10h10V8H2z"></path> </svg> </button>

<pre class="code-highlight ruby"><code><span class="k">class</span> <span class="nc">AddPositionToSlides</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="p">[</span><span class="mf">8.1</span><span class="p">]</span> <span class="k">def</span> <span class="nf">change</span> <span class="n">add_column</span> <span class="ss">:slides</span><span class="p">,</span> <span class="ss">:position</span><span class="p">,</span> <span class="ss">:integer</span> <span class="n">reversible</span> <span class="k">do</span> <span class="o">|</span><span class="n">dir</span><span class="o">|</span> <span class="n">dir</span><span class="p">.</span><span class="nf">up</span> <span class="k">do</span> <span class="n">execute</span> <span class="o">&lt;&lt;~</span><span class="no">SQL</span><span class="sh"> UPDATE slides SET position = ranked.rank FROM ( SELECT id, ROW_NUMBER() OVER (PARTITION BY carousel_id ORDER BY created_at, id) AS rank FROM slides ) AS ranked WHERE slides.id = ranked.id </span><span class="no"> SQL</span> <span class="k">end</span> <span class="k">end</span> <span class="n">add_index</span> <span class="ss">:slides</span><span class="p">,</span> <span class="p">[</span><span class="ss">:carousel_id</span><span class="p">,</span> <span class="ss">:position</span><span class="p">],</span> <span class="ss">unique: </span><span class="kp">true</span> <span class="k">end</span> <span class="k">end</span> </code></pre> </div> <p>Don't skip the backfill. <code>acts_as_list</code> gets confused when some rows have a position and some are <code>NULL</code>, and on the first move you'll see records jumping to weird places. <code>PARTITION BY carousel_id</code> gives every carousel its own 1, 2, 3, which is what the scope from the next step expects.</p> <p>The backfill also makes the unique index safe to add. With that index in place, the database just refuses two slides at the same position. And <code>acts_as_list</code> is smart about it: when it sees a unique index it switches to updating rows one by one (<code>sequential_updates</code>), so it doesn't trip over it.</p> <p>(This SQL is PostgreSQL. On MySQL do it in Ruby with <code>each.with_index(1)</code> and <code>update_column</code>.)</p> <h3>2. Add <code>acts_as_list</code> with a scope</h3> <div class="code-highlight code-block-wrapper"> <button type="button" class="code-copy-button" data-controller="clipboard" data-clipboard-success-message-value="Copied!" data-clipboard-error-message-value="Failed to copy!" data-clipboard-text='# Gemfile gem "acts_as_list" '> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewbox="0 0 20 20" fill="currentColor" class="copy-icon"> <path d="M6 6V2c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-4v4a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V8c0-1.1.9-2 2-2h4zm2 0h4a2 2 0 0 1 2 2v4h4V2H8v4zM2 8v10h10V8H2z"></path> </svg> </button> <pre class="code-highlight ruby"><code><span class="c1"># Gemfile</span> <span class="n">gem</span> <span class="s2">"acts_as_list"</span> </code></pre> </div><div class="code-highlight code-block-wrapper"> <button type="button" class="code-copy-button" data-controller="clipboard" data-clipboard-success-message-value="Copied!" data-clipboard-error-message-value="Failed to copy!" data-clipboard-text="class Slide &lt; ApplicationRecord belongs_to :carousel acts_as_list scope: :carousel end

class Carousel < ApplicationRecord has_many :slides, -> { order(:position) }, dependent: :destroy end "> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewbox="0 0 20 20" fill="currentColor" class="copy-icon"> <path d="M6 6V2c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-4v4a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V8c0-1.1.9-2 2-2h4zm2 0h4a2 2 0 0 1 2 2v4h4V2H8v4zM2 8v10h10V8H2z"></path> </svg> </button>

<pre class="code-highlight ruby"><code><span class="k">class</span> <span class="nc">Slide</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span> <span class="n">belongs_to</span> <span class="ss">:carousel</span> <span class="n">acts_as_list</span> <span class="ss">scope: :carousel</span> <span class="k">end</span> <span class="k">class</span> <span class="nc">Carousel</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span> <span class="n">has_many</span> <span class="ss">:slides</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">order</span><span class="p">(</span><span class="ss">:position</span><span class="p">)</span> <span class="p">},</span> <span class="ss">dependent: :destroy</span> <span class="k">end</span> </code></pre> </div> <p>Now every slide gets <code>move_higher</code>, <code>move_lower</code>, <code>move_to_top</code>, <code>move_to_bottom</code> and <code>insert_at(n)</code>. New slides go to the bottom of their own carousel and positions start at 1.</p> <p>A small trap I want to warn you about: don't add <code>validates :position, presence: true</code>. <code>acts_as_list</code> sets the position after validations run, so a new slide fails a validation it would pass a millisecond later. The README mentions it, but it's very easy to miss.</p> <p><code>acts_as_list</code> has been around forever. It has more than 76 million downloads on RubyGems (October 2026), so whatever weird case you hit, someone else hit it before you.</p> <p>Also notice that the order lives on the <a href="https://avohq.io/glossary/associations" target="_blank">association</a> and not in a <code>default_scope</code> on <code>Slide</code>. I'll come back to that one.</p> <h3>3. A route and a controller action</h3> <div class="code-highlight code-block-wrapper"> <button type="button" class="code-copy-button" data-controller="clipboard" data-clipboard-success-message-value="Copied!" data-clipboard-error-message-value="Failed to copy!" data-clipboard-text="# config/routes.rb resources :carousels do resources :slides do patch :move, on: :member end end "> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewbox="0 0 20 20" fill="currentColor" class="copy-icon"> <path d="M6 6V2c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-4v4a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V8c0-1.1.9-2 2-2h4zm2 0h4a2 2 0 0 1 2 2v4h4V2H8v4zM2 8v10h10V8H2z"></path> </svg> </button> <pre class="code-highlight ruby"><code><span class="c1"># config/routes.rb</span> <span class="n">resources</span> <span class="ss">:carousels</span> <span class="k">do</span> <span class="n">resources</span> <span class="ss">:slides</span> <span class="k">do</span> <span class="n">patch</span> <span class="ss">:move</span><span class="p">,</span> <span class="ss">on: :member</span> <span class="k">end</span> <span class="k">end</span> </code></pre> </div><div class="code-highlight code-block-wrapper"> <button type="button" class="code-copy-button" data-controller="clipboard" data-clipboard-success-messa

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →