Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1paginationwill-paginate

I want to have a next and previous link that featches the next and previous article


In a simple blog application where someone can read an article and decide to read the next article without going through the list of articles again but click the next button and it takes the person to the next article on this list. How can this be done. I have worked with willpaginate and kaminari and they are both great plugins for pagination.

So now in the show action i want to have a next and previous link that featches the next and previous article how do i do this

simple code sample below to work with

def show
  @article = Article.find(params[:id])
end

Solution

  • You could add a method to Article to get the next and previous articles depending on what you mean by next and previous - i.e. what order you want the articles in.

    E.g. with created_at used to define the order

    def next
      self.class.find(
        :first, 
        :conditions => ["created_at > ?", self.created_at], 
        :order => 'created_at, id')
    end
    
    def previous
      self.class.find(
        :first, 
        :conditions => ["created_at < ?, self.created_at],
        :order => 'created_at desc, id desc')
    

    That assumes that nothing has the same created at date which might be a bit too simplistic so you might want to check against the id too. Something like:

        :conditions => ["created_at > ? or (created_at = ? and id > ?)", self.created_at, self.created_at, self.id]
    

    If you just want to order by id then it is even more trivial as the ids can never be the same:

    def next
      self.class.find(:first,
        :conditions => ['id > ?', self.id],
        :order => 'id')
    end
    
    def previous
      self.class.find(:first,
        :conditions => ['id < ?', self.id],
        :order => 'id desc')
    end