Rails: “Next post” and “Previous post” links in my

2020-01-27 11:50发布

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 this?

Thanks!

7条回答
迷人小祖宗
2楼-- · 2020-01-27 12:48

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
查看更多
登录 后发表回答