Hey all, I've just put together a little plugin to easily access the neighbours of a given model in a particular order. Read on if interested. Install: script/plugin install http://svn.viney.net.nz/things/rails/plugins/acts_as_ordered Usage: class Person < ActiveRecord::Base acts_as_ordered :order => 'first_name' end Say you have people with first names of Adam, Jonathan and Robert: p = Person.find_by_first_name('Jonathan') p.next # Robert p.previous # Adam p.previous.previous # Adam (does not wrap around to end) p.next.next # Robert (does not wrap around to start) If you want the next and previous methods to wrap around the ends, use: acts_as_ordered :order => 'first_name', :wrap => true You can use this in a application to be able to quickly browse through people. Eg: class PersonController < ApplicationController def view_neighbour # params[:direction] is passed off the page as 'next' or 'previous' @person = Person.find(params[:id]).send(params[:direction]) render :action => 'view' end end Problems, comments, and suggestions all welcome. Cheers, -Jonathan.
on 2006-03-30 11:26
on 2006-03-30 13:56
I've just added the ability to jump by more than one at a time. Say you have people with first names of Adam, Jonathan and Robert: # Without wrapping (clamps to ends) p = Person.find_by_first_name('Jonathan') p.next(2) # Robert p.next(100) # Robert p.previous(100) # Jonathan # With wrapping (wraps around ends as many times as you like) p = Person.find_by_first_name('Jonathan') p.next(8) # Adam p.previous(17) # Robert It will clamp or wrap around the ends depending on whether or not you specify :wrap => true. Cheers, -Jonathan.
on 2006-03-30 23:40
Wow! That's really cool. Thanks,