2
1

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 3 years have passed since last update.

Rails 超簡単 並べ替え機能 ソート検索 (古い順・最新順)

Last updated at Posted at 2021-03-17

はじめに

筆者は 大学生限定 プログラミングコミュニティ 『GeekSalon』で活動している者です!
もし少しでも興味がありましたら、ぜひお話を聞きにきてくださいね♪

では本題。
YouTubeでよく人気順に並べ替えたり、最新の動画順に並べ替えたりしますよね!?!?

意外とこの部類の記事がなかったので、今回は似た機能を実装してみたので紹介しやあす!!
(いいね順はいいねを実装するのがちょっとめんどくさいので後ほど更新いたします、、、やってることは同じで応用するだけです)

もっとハイテクなやり方があるかもしれませんが、初心者でもできるような簡単なやり方で実装しています、ご理解くださいませぇ。

STEP1

viewで使うためにコントローラーで並べ替えた投稿を変数に代入します。
この時、条件分岐によって並べ替え検索の下準備をします。

posts_controller.rb
  def index
    if params[:search] == ''
      @posts= Post.all.order(id: "DESC")
    elsif params[:search] == 'newpost'
      @posts= Post.all.order(id: "DESC")
    elsif params[:search] == 'oldpost'
      @posts= Post.all
    end
  end

@posts= Post.all.order(id: "DESC")は上からidが大きい順、つまり最新の投稿順にソートするためのコードです。

条件分岐を言葉で上から解説すると、、、

もし並べ替え検索欄に空文字が含まれている、つまり特に検索されていなければ最新順にソートした全ての投稿を@postsに代入
もし並べ替え検索欄にnewpostという文字列が送られたら、最新順にソートした全ての投稿を@postsに代入
もし並べ替え検索欄にoldpostという文字列が送られたら、古い順にソートした全ての投稿を@postsに代入

STEP2

並べ替え検索のviewページを整えましょう。

posts/index.html.erb
 <h3>並べ替え</h3>
 <%= form_tag({controller:"posts",action:"index"}, method: :get) do %>
   <%= select_tag("search", options_for_select([['---並べ替え選択---', ''], ['最新の投稿', 'newpost'], ['古い投稿', 'oldpost']])) %>
   <%= submit_tag '並べ替える'  %>
 <% end %>

  <% @posts.each do |t| %>
      <%= t.body %>
      <%= t.created_at %>
  <% end %>

select_tag を使って、特定のvalueを送っているのがミソですね!

最後に

いかがでしたでしょうかああああ

結構雑に書いちゃった&&いいね順めんどくさがってしまったので、時間取れた時にまた改修いたします🙇‍♂️

現段階で補足修正等ございましたら、編集リクエスト送ってくださいまし。

それではバイちゃ〜〜👋

2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?