Next, Previous Records Using Named Scope

Posted by keruilin on Stack Overflow See other posts from Stack Overflow or by keruilin
Published on 2010-05-02T20:17:37Z Indexed on 2010/05/02 20:58 UTC
Read the original article Hit count: 391

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord