Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

成果

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

DURIAN_JADE
ハナコです。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away