LoginSignup
6
7

More than 3 years have passed since last update.

カテゴリ別ランキング機能の実装

Last updated at Posted at 2020-01-27

概要

全体のランキング機能は他の記事を参考にして割と簡単にできたのですが、カテゴリ別ランキングの表示が分からずに一苦労したので纏めます。

スポット(Post)ごとに写真(Image)が投稿でき、写真ごとにコメント(Comment)が投稿できるアプリケーションを作成しております。
Imageにいいねをつけることができ、Post毎にいいね順で並び替えて表示させます。

ビューはHamlで書いております。
今回はCommentテーブルは関係ないので省略して書きます。
作成途中のため、細かいところはご容赦くださいませ。

前提条件

Post、Imageテーブルは作成済み。
いいね機能は実装済み。(Like count)

ルーティング

routes.rb
  resources :posts, only: [:index, :new, :create, :edit, :update] do
    resources :images, only: [:index, :new, :create, :show]

コントローラー

images_controller
@all_ranks = Image.find(Like.group(:image_id).order('count(image_id) desc').limit(9).pluck(:image_id))
@post_ranks = @all_ranks.select{ |image| image.post_id == @post.id }

@all_ranksにてまずは全体のいいねランキングを作成しております。
その後で@post_ranksにてカテゴリ別(POST別)に分けます。

ビュー

      .image__contents
        - @post_ranks.each do |image|
         .image__contents__content
            = image_tag(image.image)

これで@all_ranksのlimit(9)で指定した数までカテゴリ別でランキングが表示されるようになります。
ちなみに@all_ranksをそのまま表示させれば総合ランキングです。

selectメソッド便利ですね。

以上となります。間違いありましたらご指摘お願いいたします!

6
7
1

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
7