开发者

How do I find the items immediately before and after a specific one in an ordered array, using Ruby on Rails?

开发者 https://www.devze.com 2023-01-09 15:42 出处:网络
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.

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 开发者_JAVA百科and the question after @question in that list?


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


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")
0

精彩评论

暂无评论...
验证码 换一张
取 消