2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

テーブルにソート機能をつける

Posted at

実現したい仕様

  • テーブルのヘッダー文言の初期表示は「登録日時△」
  • テーブルのヘッダーをクリックすると、そのカラムの内容でソートされ、ヘッダー文言は以下のようになる
    • 「登録日時△」->「登録日時▼」(降順ソートになる)
    • 「登録日時▼」->「登録日時▲」(昇順ソートになる)
    • 「登録日時▲」->「登録日時▼」(降順ソートになる)
  • 「更新日時」カラムも同様
    • 但し、「更新日時」ヘッダーをクリックすると、「登録日時」ヘッダーは「登録日時△」の表示になる(逆も同様)

実装

routes.rb
Rails.application.routes.draw do
  resources :books do
    collection do
      get :sort
    end
  end
end
  • コントローラはもっとDRYできそうです。
books_controller.rb
class BooksController < ApplicationController
  before_action :set_variable, only: [:index, :sort]

  def index
    @books = Book.all
  end

  def sort
    if params[:created_at].present?
      @created_at_num = params[:created_at].to_i

      if @created_at_num == 0
        @books = Book.order(created_at: :DESC)
        @created_at = '登録日時▼'
        @created_at_num = 1
      else
        @books = Book.order(created_at: :ASC)
        @created_at = '登録日時▲'
        @created_at_num = 0
      end

    elsif params[:updated_at].present?
      @updated_at_num = params[:updated_at].to_i

      if @updated_at_num == 0
        @books = Book.order(updated_at: :DESC)
        @updated_at = '更新日時▼'
        @updated_at_num = 1
      else
        @books = Book.order(updated_at: :ASC)
        @updated_at = '更新日時▲'
        @updated_at_num = 0
      end

    else
      @books = Book.all
    end
    render :index
  end

  private

  def set_variable
    @created_at = '登録日時△'
    @updated_at = '更新日時△'
    @created_at_num = 0
    @updated_at_num = 0
  end
end
  • Bootstrapの記述があります。見辛かったらすみません。
index.html.slim
.container

  h1.mb-3 書籍一覧

  - if @books.size > 0
    table.table.table-bordered
      thead.thead-light
        tr
          th タイトル
          th 著者
          th.pointer onclick='window.location="#{sort_books_path(created_at: @created_at_num)}"' role="link"
            = @created_at
          th.pointer onclick='window.location="#{sort_books_path(updated_at: @updated_at_num)}"' role="link"
            = @updated_at
      tbody
        - @books.each do |book|
          tr
            td
              = book.title
            td
              = book.author
            td
              = book.created_at
            td
              = book.updated_at
  - else
    .mt-5.text-center 該当のデータはございません。

まとめ

  • あんまりこれといった学びポイントが無かった?ですかね。。。とりあえず冗長さが感じられるので、ググりながらもっといい書き方無いか探してみます。
2
6
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
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?