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

前端 未结 7 1142
闹比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:21

    You really just need to run 2 queries, one for each of "prev" and "next". Lets assume you have a created_at column.

    Psuedo-code:

    # get prev
    select * from posts where created_at < #{this_post.created_at} order by created_at desc limit 1
    
    # get next
    select * from posts where created_at > #{this_post.created_at} order by created_at desc limit 1
    

    Of course "this_post" is the current post.

    If your posts are stored with an auto_increment column and you dont re-use IDs you can just use the id column in place of created_at - the id column should already be indexed. If you want to use the created_at column then you will definitely want to have an index on that column.

提交回复
热议问题