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.