1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rails Stimulus-Sortableで並び替え

1
Posted at

背景

  • acts_as_listというgemを利用して、Bookモデルに紐づくpagesを入れ替える実装をしてた
  • しかしフロントがだいぶイケてない仕様になってしまったので、ドラックアンドドロップで良い感じにできる方法ないかなと
  • 先輩に相談をするとSortableが良さげということなので、実際に使ってみた

インストール

$ yarn add @stimulus-components/sortable sortablejs @rails/request.js

コントローラの登録

app/javascript/controllers/index.jsに下記を記述して、コントローラを登録します

import { Application } from '@hotwired/stimulus'
import Sortable from '@stimulus-components/sortable'

const application = Application.start()
application.register('sortable', Sortable)
  • import Sortable from '@stimulus-components/sortable'

Sortableコンポーネントをインポートします
これが並び替えを可能にしてくれるコンポーネントです

  • const application = Application.start()

Stimulusアプリケーションを開始して、そのインスタンスをapplicationに格納

  • application.register('sortable', Sortable)

sortableという名前でコンポーネントを登録

ビューにsortable属性を追加する

仮に下記のようなリストを用意したとします

<ul class="list-group" data-controller="sortable" data-sortable-animation-value="150">
  <% @pages.each do |page| %>
    <li class="list-group-item d-flex" data-sortable-update-url="<%= page_position_path(page) %>">
    </li>
  <% end %>
</ul>
  • data-controller="sortable"

sortable-controllerと紐付けます

  • data-sortable-update-url

ページを入れ替えて、完了したタイミングで更新される並び順を送信する先のURLを指定します

この時点でページの移動自体は、ドラックアンドドロップできると思います

ページ数のカラムを更新する

今回はBookが複数のPageを保持できる関係だと仮定します

page.rb
class Page < ApplicationRecord
  acts_as_list scope: :book
end
pages/positions_controller.rb
class Pages::positionsController < ApplicationController
  def update
    @page.insert_at!(params[:position].to_i)
  end
end

acts_as_listinsert_at!を使用して、例外エラーでページ移動ができなかった場合にも対処します

感想

  • 意外と簡単に実装できた。JSの仕組みがあやふやなのはなんとかしたい

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?