Thursday, November 27, 2008

Ruby on Rails : Get Next ActiveRecord Element?

Ok, file this one under "surely there's a way to do this that I'm just missing."

You're in a typical scaffold where you've gotten your list of Widgets, and now you're on /show/ for a particular Widget, say maybe #123. What I want to say on that page, with only the single Widget#123 for context, "go on to the next element." Or the previous one. You can't do it strictly by ID, because your IDs might not be continuous (i.e. the next one from 123 might be 125).

Anybody got the trick?

2 comments:

fsainz said...

I'm using these methods, but there's got to be a better way


Class Widget
def self.previous_from id
prev=find_by_sql ["select max(id) from widgets where id < ?", id]
prev_id=prev.first.attributes["max(id)"]
self.find(prev_id)
end
def self.next_from id
_next=self.find_by_sql ["select min(id) from widgets where id > ?", id]
next_id= _next.first.attributes["min(id)"]
self.find(next_id)
end

Dom said...

ahh, i was just wondering the exact same thing! seems like there should be a shortcut for this, as fsainz mentioned...