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

前端 未结 7 1071
闹比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:39

    I used the model methods as below to avoid the issue where id + 1 doesn't exist but id + 2 does.

    def previous
      Post.where(["id < ?", id]).last
    end
    
    def next
      Post.where(["id > ?", id]).first
    end
    

    In my view code, I just do this:

    <% if @post.previous %>
      <%= link_to "< Previous", @post.previous %>
    
    <% if @post.next %>
      <%= link_to "Next >", @post.next %>
    
    0 讨论(0)
提交回复
热议问题