My simplified rails app looks like this
# chapter.rb
has_many :sections
has_many :videos, through: :sections
# section.rb
belongs_to :chapter
has_many :videos
# video.rb
belongs_to :section
has_many :votes
# vote.rb
belongs_to :video
What I want to do is find the top 5 currently popular videos for a given chapter, which would mean ordering the videos by the number of votes it has received within the last month (and limiting to 5 results, obviously).
I wanted to write a popular_videos method in my Chapter model, and I think this requires a find_by_sql query, right? But I don’t know enough sql to write this query.
The votes table has a created_at column, and I’m using postgres for my database. Any help is greatly appreciated.
I don’t know anything about rails, but guessing at the table structures from what’s in the question, I would think SQL like the following would be one way to provide what you want:
If you’re running PostgreSQL 9.1 or later, you can probably omit
video.namefrom theGROUP BYlist.