前提
各エリアに属したイベントに,ユーザーがいいねをできるサイトを制作しています。
実現したいこと
エリア毎のいいねランキングを作成したい。画像はいいね数が多い順に並んでいない。
![
試したこと
ランキングを作成するために、下記のようにcontrollerを記述した。
Favoriteモデルを参照→area_id:1に属したeventを取得。→event_idが多い順に並び替える(いいねが多い順)。
controller
class HomesController < ApplicationController def top @events_ranking_area= Event.where(area_id: 1, id: Favorite.group(:event_id).order('count(event_id) desc').pluck(:event_id)) end end
コード詳細
model
#ユーザーモデル class User < ApplicationRecord has_many :favorites end #エリアモデル class Area < ApplicationRecord has_many :events end #イベントモデル class Event < ApplicationRecord belongs_to :area has_many :favorites end #いいねモデル class Favorite < ApplicationRecord belongs_to :user belongs_to :event end
###問題点
area_id:1に属したeventの取得はできる。しかし、event_idが多い順に並び替えられない。
分かる方がいましたら、ご教示いただきたく思います。
よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。