LoginSignup
15
18

More than 5 years have passed since last update.

RailsでテーブルのSortかつPaginationを実現できた

Last updated at Posted at 2018-12-27

成果

test.gif

実現方法

「rails table sort」というキーワードでグーグル検索したら、下記の文章を発見。
https://www.virment.com/rails-sortable-table/
大変助かりましたので作者に感謝を申し上げたい。

この文章はSortだけなのでPaginationを加えたらどうするのか自分で試した上、
下記に整理します。

①Help methodを追加
transactions_helper.rb
module TransactionsHelper

    def sortable(column, title = nil)
        title ||= column.titleize
        css_class = (column == sort_column) ? "current #{sort_direction}" : nil
        direction = (column == sort_column && sort_direction == "asc") ? "desc" : "asc"
        link_to title, {:sort => column, :direction => direction}, {:class => css_class}
    end

    def sort_direction
        %w[asc desc].include?(params[:direction]) ?  params[:direction] : "asc"
    end

    def sort_column
        Transaction.column_names.include?(params[:sort]) ? params[:sort] : "occurred_date"
    end

end

Ruby初心者なので正直言うとこのコードはまだハッキリ分からないけど、一応結果的にできるようになったのでとりあえず嬉しい。後で十分理解できるように頑張っていきます。

②controllerにindexを下記のように修正
transactions_controller.rb
include TransactionsHelper

  def index
    @transactions = Transaction.paginate(page: params[:page], per_page: 8).order(sort_column + ' ' + sort_direction)
  end
③index.html.erbを修正
index.html.erb
<%= will_paginate %>    <-----追加
<中略>
<th><%= sortable "occurred_date", "発生日" %></th>
<略>

以上。

【2018年12月29日更新】
上記のコードを理解できました。
自分で書き直したコードは以下になります。

transactions_helper.rb
    def sort_asc(column_to_be_sorted)
        link_to "▲", {:column => column_to_be_sorted, :direction => "asc"}
    end

    def sort_desc(column_to_be_sorted)
        link_to "▼", {:column => column_to_be_sorted, :direction => "desc"}
    end

    def sort_direction
        # If params[:direction] is nil, set sort_direction to "desc" by default
        %W[asc desc].include?(params[:direction]) ? params[:direction] : "desc"
    end

    def sort_column
        # If params[:column] is nil, set sort_column to "occurred_date" by default
        Transaction.column_names.include?(params[:column]) ? params[:column] : "occurred_date"
    end

transactions/index.html.erb:
image.png

最終効果:
test.gif

15
18
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
15
18