0
0

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 1 year has passed since last update.

【Rails】投稿のソート機能(kaminari)

Posted at

投稿の表示順を変えるソート機能を実装したのでまとめておきます。

完成するとこんな感じです。
Image from Gyazo

kaminariをインストール

gemファイルに記載しbundle install

gem 'kaminari'

モデル

  scope :latest, -> {order(created_at: :desc)} #新しい順
  scope :old, -> {order(created_at: :asc)}  #古い順
  scope :random, -> { order('RAND()') } #ランダム

コントローラー

def index
  @posts = Post.all
  if params[:latest]
    @posts = Post.latest.page(params[:page]).per(1)
  elsif params[:old].present?
    @posts=Post.old.page(params[:page]).per(1)
  elsif params[:random].present?
    @posts = Post.random.page(params[:page]).per(1)
  else
    @posts = Post.all.page(params[:page]).per(1)
  end
end

ビュー

        <div class="sort">
        <%= link_to '新しい順', posts_path(latest: "true") %>
        |
        <%= link_to '古い順', posts_path(old: "true") %>
        |
        <%= link_to 'ランダム', posts_path(random: "true") %>
        </div>
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?