开发者

How do I find the next record in an ActiveRecord set?

I am working in Padrino and have this in my controller

@work.find_by_id(params[:id])

I want to add prev/next buttons into my view, and so must开发者_如何学C be able to get the path to the next item on the list. How can I do that with ActiveRecord?


You may want to checkout the ActsAsAdjacent plugin. I'm not sure if you can use plugins with Padrino, but the code is pretty simple, and should be able to adapt to your needs.


I use a PreviousNextable module like so:

module PreviousNextable  

  def self.included(klass)

    klass.class_eval do
      extend ActiveSupport::Memoizable 
      memoize :previous
      memoize :next
    end

  end  

  def previous
    self.class.last :order => 'name', :conditions => ['name < ?', self.name]
  end

  def next
    self.class.first :order => 'name', :conditions => ['name > ?', self.name]
  end

end

This code was adapted from an SO answer given by Ryan Bates. Your order and conditions to determine what's previous or next will likely differ. Probably you'll want to use 'created_at'.

Include the module in your model class:

class Place < ActiveRecord::Base
  include PreviousNextable  

and you're off.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜