How can I turn the following SQL query into an ActiveRecord relation so that I can expand on it with scopes?
WITH joined_table AS (
SELECT workout_sets.weigh
You are apparently trying to get the latest workout (highest id) details that match the highest weight for each user. It also appears that you are using PostgreSQL (MySQL doesn't have CTE's), correct me if I'm wrong on this.
If so, you can make use of windowing functions and simplify your query to:
SELECT * FROM (
SELECT workouts.*, workout_sets.weight,
workout_sets.id AS workout_set_id,
workout_exercises.id AS exercise_id,
ROW_NUMBER() OVER (
PARTITION BY workouts.user_id
ORDER BY workout_sets.weight DESC, workouts.id DESC ) as rowNum
FROM workouts
JOIN workout_exercises ON workout_exercises.workout_id = workouts.id
JOIN workout_sets ON workout_sets.workout_exercise_id = workout_exercises.id
) t
WHERE rowNum = 1
Which in ActiveRecord can be written as:
selected_fields = <<-SELECT
workouts.*,
workout_sets.weight,
workout_sets.id AS workout_set_id,
workout_exercises.id AS exercise_id,
ROW_NUMBER() OVER (
PARTITION BY workouts.user_id
ORDER BY workout_sets.weight DESC, workouts.id DESC) as rowNum
SELECT
subquery = Workout.joins(:workout_exercises => :workout_sets).
select(selected_fields).to_sql
Workout.select("*").from(Arel.sql("(#{subquery}) as t"))
.where("rowNum = 1")