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.

いいね数が多い順番に並び替え

Posted at

概要

投稿をいいねの順番に並び替えることができます。

controller

favorites.controller.rb
def index
    to = Time.current.at_end_of_day
    from = (to - 6.day).at_beginning_of_day
    @books = Book.includes(:favorited_users).
      sort_by {|x|
        x.favorited_users.includes(:favorites).where(created_at: from...to).size
      }.reverse
    @book = Book.new
  end
  • いいね数が多い順に表示させるためにコントローラー内で条件を定義する
  • sort_byメソッドを使っていいね数を少ない順に取り出している。最後にreverseをつけて昇順から降順に切り替えている
sort_by {|x|
  x.favorited_users.includes(:favorites).where(created_at: from...to).size
 }.reverse

model

ユーザーの情報がfavorited_usersに格納されているため、includesの引数に入れることで、事前にユーザーのデータを読み込みしている

favorite.rb
has_many :favorited_users, through: :favorites, source: :user
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?