查找按位置列轨道排序的下一个和上一个记录

时间:2011-03-08 21:33:46

标签: ruby-on-rails

>>  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">]

我需要找到一个在id 9之后的course_step(恰好是带有id 10的course_step)(如果它存在的话)

我还需要找到之前的(如果它存在)

我知道我可以手动完成循环结果,但我宁愿用SQL来做。

NEXT sql查询将是:

SELECT * FROM course_steps WHERE position >=POSITION_OF_STEP ORDER BY position LIMIT 1 OFFSET 1 

PREVIOUS sql查询将是:

SELECT * FROM course_steps WHERE position <= POSITION_OF_STEP ORDER BY position DESC LIMIT 1 OFFSET 1

我想我明白了!

1 个答案:

答案 0 :(得分:1)

class CourseStep < ActiveRecord::Base
  belongs_to :step
  belongs_to :course

  validates_uniqueness_of :step_id, :scope => :course_id

  def next_step()
    Course.find(self.course.id).course_steps.order(:position).where("position >= ?", self.position).limit(1).offset(1).first
  end

  def previous_step()
     Course.find(self.course.id).course_steps.order("position DESC").where("position <= ?", self.position).limit(1).offset(1).first
  end
end