今回はソート機能を作成しようと思い自分なりにまとめてみました
gemファイルに記載する
gem 'kaminari'
bundle installは忘れず行いましょう
modelに追加します
app/models/.rb
scope :latest, -> {order(created_at: :desc)} #新しい順に
scope :old, -> {order(created_at: :asc)} #古い順に
scope :star_count, -> {order(star: :desc)} #評価の多い順に
コントローラーに追加する
controllers/games_controller.rb
def index
@books = Book.all
#ここから追加
if params[:latest] #条件定義
@books = Book.latest.page(params[:page]).per(10)
elsif params[:old].present?
@books=Book.old.page(params[:page]).per(10)
elsif params[:star_count]
@books = Book.star_count.page(params[:page]).per(10)
else
@games = Game.all.page(params[:page]).per(10)
end
viewsの一覧ページに追加
books/index.html.erb
<h2>本のレビュー</h2>
///ここから追加
<%= link_to '新しい順', books_path(latest: "true") %>
<%= link_to '古い順', books_path(old: "true") %>
<%= link_to '評価の高い順', books_path(star_count: "true") %>