ParsaLabs | Blog

A publication about the web and more.

Rails: Getting Next/previous Record

| Comments

Here is my solution to this common problem, but first the problem statement:

In one of my apps I have Questions that belong to certain Courses, like so:

1
2
3
4
5
6
7
class Course
  has_many :questions
end

class Question
  belongs_to :course
end

What I want to be able to do is, inside course, I’d like to show the first question (which is easy in Rails) and then when user answers it correctly, show a link to the “NEXT” question and so on. How would you go about doing that? Certainly you cannot just increment the id of the current question being displayed, and hope that id+1 is the id of the next record/question!

The solution I have come up with is the following:

1
2
3
4
5
6
7
8
9
10
11
class Question
  belongs_to :course

  def next
    self.course.questions.where("id > ?", self.id).order(id: :asc).first
  end

  def previous
    self.course.questions.where("id < ?", self.id).order(id: :desc).first
  end
end

Now, we can do:

1
2
<%= link_to 'Next', @current_question.next %>
<%= link_to 'Previous', @current_question.previous %>

Of course, this is just one way of doing it. If you (the reader) have a different/better solution, please share it with us in the comments section.

Cheers

Comments