LoginSignup
2
0

More than 1 year has passed since last update.

【Rails】acts_as_listを使用した並び替え機能

Posted at

概要

タスク管理アプリの作成で各タスクの並び替え機能を実装する為に、Gemのacts_as_listを導入。
導入手順は以下の通り。

1. gemのインストール

gemfile
gem 'acts_as_list'
ターミナル
bundle install

2. positionカラムの追加

acts_as_listpositionカラムを使用しなければならない為、並び替え機能を実装したいモデルにpositionカラムを追加.

ターミナル
% rails generate migration AddPositionToCard position:integer

3. モデルにacts_as_listを記述

acts_as_listを並べ替え機能を実装したいモデルに追記することで、データ作成時にpositionカラムにデータが入る。

models/card.rb
class Card < ApplicationRecord
  acts_as_list
end

4. コントローラーにmove_higher&move_lowerメソッドを記述

各要素を上下にひとつ動かしたいだけなので、move_highermove_lowerを使用。
他のメソッド記述方法は下記参照。
リンク:github/acts_as_list

cards_controller.rb
  def index
    @cards = Card.all.order(:position) #positionカラム順に並べる
  end

  def move_higher
    Card.find(params[:id]).move_higher #move_higherメソッドでpositionを一つ上に
    redirect_to action: :index
  end
  
  def move_lower
    Card.find(params[:id]).move_lower #move_lowerソッドでpositionを一つ下に
    redirect_to action: :index
  end

5. ルーティングの設定

上記で新規アクションを設定したので、新たにルーティングの設定。

config/routes.rb
resources :cards do
  member do
    get :move_higher
    get :move_lower
  end
end

6. ビューの編集

card/index.html.erb
<% @cards.each do |card| %>
<div class="card_arrow">
  <%= link_to "∧", move_higher_card_path(card) %>
  <%= link_to "∨", move_lower_card_path(card) %>
</div>
<% end >

動作イメージ例

上記手順で実装すると下記のような動作が行えるようになりました。
Image from Gyazo

備考

今回の実装は同期通信で実装していますが、非同期通信でもできるみたいですので、
非同期でも並び替え機能を実装できたら、記事の更新をしたいと思います。

2
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
2
0