>> c = Course.find(3).course_steps.order(:position)
=> [#<CourseStep id: 9, step_id: 4, course_id: 3, position: 1, created_at: "2011-03-08 20:57:44", updated_at: "2011-03-08 20:57:44">, #<CourseStep id: 10, step_id: 5, course_id: 3, position: 2, created_at: "2011-03-08 20:57:45", updated_at: "2011-03-08 20:57:45">, #<CourseStep id: 8, step_id: 2, course_id: 3, position: 3, created_at: "2011-03-08 20:57:42", updated_at: "2011-03-08 20:57:42">]
I need to find a course_step that is after id 9 (which happens to be course_step with id 10) (if it is exists)
I also need to find the previous (if it is exists)
I know I could manually do it be looping through the results, but I would rather do it with SQL.
The NEXT sql query would be:
SELECT * FROM course_steps WHERE position >=POSITION_OF_STEP ORDER BY position LIMIT 1 OFFSET 1
The PREVIOUS sql query would be:
SELECT * FROM course_steps WHERE position <= POSITION_OF_STEP ORDER BY position DESC LIMIT 1 OFFSET 1
I think I got it!
1 Answer