Does ActiveRecord offer a simple solution to get previous/next records relative to a certain record? For instance, say I have this table: PEOPLE id | name 1 | john 2 | mary 3 | bob Using p = Person.find(2), is it possible to get the previous (john) and next (bob) records using perhaps something like p.previous and p.next? If not, how can I do this without resorting to ugly queries? Thanks in advance
on 2007-05-01 10:57
on 2007-05-01 11:45
Try my acts_as_ordered plugin: http://svn.viney.net.nz/things/rails/plugins/acts_... -Jonathan.
on 2007-05-01 13:00
Exactly what I needed, thanks!
on 2007-05-01 14:13
Toulax, > Using p = Person.find(2), is it possible to get the previous (john) > and next (bob) records using perhaps something like p.previous and > p.next? If not, how can I do this without resorting to ugly queries? If you - only need next() - use MySql (optional) simply add this in environment.rb : class ActiveRecord::Base def next self.class.find(:first, :conditions => ['id > ?', self.id]) end end For non-MySql db, you might have to add :order => 'id asc' to the query. (see: http://weblog.jamisbuck.org/2007/4/6/faking-cursor...) Alain Ravet http://blog.ravet.com