LoginSignup
6
13

More than 1 year has passed since last update.

[Ruby on rails]過去一週間でいいねの多い順に投稿を表示

Last updated at Posted at 2021-07-06

初めに

学習を始めたばかりです。理解不足、誤りがありましたら、コメント頂けますと幸いです。

アソシエーション記述

has_many :favorited_users, through: :favorites, source: :user 追記します。

book.rb
class Book < ApplicationRecord
  belongs_to :user
  has_many :favorites, dependent: :destroy
  has_many :favorited_users, through: :favorites, source: :user #ここです!
  has_many :book_comments, dependent: :destroy
  validates :title, presence: true
  validates :body, presence: true, length: { maximum: 200 }

  def favorited_by?(user)
    favorites.where(user_id: user.id).exists?
  end
end

favorited_usersは、favoritesテーブルを通って、userモデルのデータ持ってくるぞ〜ってことでしょうか。

参考・・特に変更してないfavorite.rbのファイル

perl:favorite.rb
class Favorite < ApplicationRecord
belongs_to :user
belongs_to :book
end

コントローラー

books_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 {|a,b| 
        b.favorited_users.includes(:favorites).where(created_at: from...to).size <=> 
        a.favorited_users.includes(:favorites).where(created_at: from...to).size
      }
    @book = Book.new
  end

以下、ページネーションを使うverです。

  def index
    to  = Time.current.at_end_of_day
    from  = (to - 6.day).at_beginning_of_day
    books = Book.includes(:favorited_users).
      sort {|a,b| 
        b.favorited_users.includes(:favorites).where(created_at: from...to).size <=> 
        a.favorited_users.includes(:favorites).where(created_at: from...to).size
      }
     @books=Kaminari.paginate_array(books).page(params[:page]).per(25)
     @book = Book.new
  end

むずううう。

(参考資料)1週間分のレコードを取り出す

to / form /created_atの記述については以下を参照し理解できました。
今回は1週間分のレコードを取り出してます!

(参考資料)includesとは??

@books = Book.includes(:favorited_users).```では、booksモデルからデータを取得するときに、favorited_usersモデルのデータもまとめて取得しています。
以下の記事でincludesとN+1問題について記載しました。

(参考資料)ソートで並び変える

以下の記事を参照し理解しました。

sort{|a, b| a.to_i <=> b.to_i }だと、昇順になりますが、今回bを先に記述してるので降順(多い順)に並び変えができるのだと理解しました。

6
13
2

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
6
13