In my Rails app, I have the following PostgreSQL query to find the most commented story in the past week.
last_week = Date.today() - 7
most_commented_comments = Comment.find_by_sql("SELECT story_id, COUNT(*) AS total FROM comments WHERE created_at >= (CAST '#{last_week}' AS date) GROUP BY story_id ORDER BY 2 DESC LIMIT #{limit}")
I’m running into some cross-platform compatibility issues, especially with the created_at >=... clause and I’d like to make this a less brittle query overall. However, I can’t seem to find a way to fit a complex query like this into the ActiveRecord wrappers given by Rails. Is it possible?
I think I figured out a much better way.