LoginSignup
21
23

More than 5 years have passed since last update.

【rails】クリックでソートの昇順・降順を切り替え

Posted at

scaffoldで作られた投稿一覧をクリックでソートできる仕様にしたい。

controllerの設定

orderを(params[:sort])と設定する

posts_controller.rb
  def index
    @posts = Post.all.order(params[:sort])
  end

viewの設定

クリックしたら昇順・降順と切り替わるように設定する

index.html.haml
%thead
    %tr
        - def sortTh(a,contName)
            - if request.fullpath.include?('desc')
                - link_to a, sort: contName
            - else
                - link_to a, sort: "#{contName} desc"
        # %th= sortTh('[表示]','[変数名]')
        %th= sortTh('投稿日','postdate')
        %th= sortTh('タイトル','title')
        %th
        %th
%tbody
    %tr
        - @posts.each do |post|
        # %td= post.[変数名]
        %td= post.postdate
        %td= post.title
        %td= link_to '詳細', post
        %td= link_to '編集', edit_post_path(post)

これにて設定完了

ソートの状態を指定してリンクさせたい

= link_to '投稿一覧へ', post_path(sort: '[変数名]')

[変数名]でソートさせるよう、パラメータを作ってくれる。

21
23
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
21
23