views:

39

answers:

2

I have an array of 'questions' ordered according to their number of votes, and want to show the question immediately before and immediately following the currently-selected question.

Let's say the currently-selected question is stored in the variable @question, and I'm showing a list of other questions associated with the same user. This code orders that list according to number of votes:

questions = Question.find(:all, :conditions => {:user => @question.user}).sort { |q1,q2| q2.votes.length <=> q1.votes.length}

Now how do I pick out just the question before and the question after @question in that list?

+1  A: 

Updated my answer. I figured you guys would get the gist from the first post but here is a more elaborated example.

Can't you do something simple like:

@questions = user.questions.sort_by{ |q| -q.votes.length }
current_question_index = @questions.index(@question)
@prev_question = @questions[current_question_index-1]
@next_question = @questions[current_question_index+1]

It's more lines but just uses simple array manipulation

nicholasklick
Do you need something more than this, as in do you need an efficient database query to pick only those out? If you can give the nature of the data maybe I can give you a specific query to get that information...? Usually you can do something like subtracting the number of votes from the number of your current question, and then wrap that in a select which selects the one with the smallest of the positive results or greatest of the negatives.
Dmitriy Likhten
This fails when removing records, you eventually could get a set of consecutive ID's like these [1,2,4,6,10,11] making current_question.id+-1 fail.
jpemberthy
Wouldn't this answer just sort by the question id, rather than the number of votes?
kateray
Worked! I'm a ruby-nuby, so thanks for walking me through it.
kateray
A: 

I would refer to time stamps.

prev = Question.first(:conditions => ["created_at < ?", @question.created_at], :order => "created_at DESC")
prev = Question.first(:conditions => ["created_at > ?", @question.created_at], :order => "created_at ASC")
skalee