Rails: “Next post” and “Previous post” links in my show view, how to?

前端 未结 7 1156
闹比i
闹比i 2020-12-01 00:51

I\'m new in Rails... smile

In my blog aplication I want to have a \"Previous post\" link and a \"Next post\" link in the bottom of my show view.

How do I do

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 01:22

    If each title is unique and you need alphabetical, try this in your Post model.

    def previous_post
      self.class.first(:conditions => ["title < ?", title], :order => "title desc")
    end
    
    def next_post
      self.class.first(:conditions => ["title > ?", title], :order => "title asc")
    end
    

    You can then link to those in the view.

    <%= link_to("Previous Post", @post.previous_post) if @post.previous_post %>
    <%= link_to("Next Post", @post.next_post) if @post.next_post %>
    

    Untested, but it should get you close. You can change title to any unique attribute (created_at, id, etc.) if you need a different sort order.

提交回复
热议问题