Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next, Previous Records Using Named Scope

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?

like image 666
keruilin Avatar asked Dec 22 '22 03:12

keruilin


1 Answers

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.

like image 144
Sam Phillips Avatar answered Jan 08 '23 12:01

Sam Phillips