Skip to content

Instantly share code, notes, and snippets.

@skarger
Created June 12, 2019 19:04
Show Gist options
  • Select an option

  • Save skarger/9d3fdb7b884b71e27261136ec4dc5837 to your computer and use it in GitHub Desktop.

Select an option

Save skarger/9d3fdb7b884b71e27261136ec4dc5837 to your computer and use it in GitHub Desktop.
class Workout < ApplicationRecord
belongs_to :sport
scope :most_recent_by_sport, -> do
from(
<<~SQL
(
SELECT workouts.*
FROM workouts JOIN (
SELECT sport_id, max(created_at) AS created_at
FROM workouts
GROUP BY sport_id
) latest_by_sport
ON workouts.created_at = latest_by_sport.created_at
AND workouts.sport_id = latest_by_sport.sport_id
) workouts
SQL
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment