これまでに作った機能について簡単にまとめていく。
今回は、
ソート(並び替え)機能の作成
前提条件
一覧画面が作成されていること
使用モデル
Blogモデル
| カラム | データ型 | |
|---|---|---|
| 1 | title | string |
| 2 | content | text |
| 3 | likes_count | integer |
スコープの作成
更新日時順にソートする
app/models/blog.rb
class Blog < ApplicationRecord
scope :latest, -> {order(updated_at: :desc)}
end
リンクの作成
app/views/blogs/index.html.erb
<%= link_to '更新日時でソートする', blogs_path(sort_update: "true") %>
コントローラーの設定
sort_updateのパラメーターの有無による条件分岐
app/controllers/blogs_controller.rb
class BlogsController < ApplicationController
def index
if params[:sort_update]
@blogs = Blog.latest
else
@blogs = Blog.all
end
end
end
以上で作成完了
