views:

38

answers:

2

I have a model for which I want to retrieve the next record(s) and previous record(s). I want to do this via a named_scope on the model, and also pass in as an argument the X number of next/previous records to return.

For example, let's say I have 5 records:

  • Record1
  • Record2
  • Record3
  • Record4
  • Record5

I want to be able to call Model.previous or Model.previous(1) to return Record2. Similarly, I want to be able to call Model.next or Model.next(1) to return Record4. As another example I want to be able to call Model.previous(2) to return Record3. I think you get the idea.

How can I accomplish this?

+1  A: 

Hey,

To implement something like 'Model.previous', the class itself would have to have a 'current' state. That would make sense if the 'current' record (perhaps in a publishing scheduling system?) was Record3 in your example, but your example doesn't suggest this.

If you want to take an instance of a model and get the next or previous record, the following is a simple example:

class Page < ActiveRecord::Base
  def previous(offset = 0)    
    self.class.first(:conditions => ['id < ?', self.id], :limit => 1, :offset => offset, :order => "id DESC")
  end

  def next(offset = 0)
    self.class.first(:conditions => ['id > ?', self.id], :limit => 1, :offset => offset, :order => "id ASC")
  end
end

If so you could do something like:

@page = Page.find(4)
@page.previous

Also working would be:

@page.previous(1)
@page.next
@page.next(1)

Obviously, this assumes that the idea of 'next' and 'previous' is by the 'id' field, which probably wouldn't extend very well over the life of an application.

If you did want to use this on the class, you could perhaps extend this into a named scope that takes the 'current' record as an argument. Something like this:

named_scope :previous, lambda { |current, offset| { :conditions => ['id < ?', current], :limit => 1, :offset => offset, :order => "id DESC" }}

Which means you could call:

Page.previous(4,1)

Where '4' is the id of the record you want to start on, and 1 is the number you want to navigate back.

Sam Phillips
How about the case where 'next' and 'previous' is by the 'created_at' field?
keruilin
Simply change the queries so that all references to 'id' (including the :order clause) are changed to 'created_at', and it should work fine.
Sam Phillips
A: 

I added this feature into my gem by_star last month. It may have some other features you're interested in, so check it out.

It works by you having an existing record and then calling previous or next on that:

Page.find(:last).previous
Ryan Bigg
This gem looks slick. Tried installing it, but had some trouble. Any documentation that says how to get it running?
keruilin
Do you need to use include or require statement?
keruilin
@keruilin: What trouble precisely did you have?
Ryan Bigg