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

前端 未结 7 1165
闹比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:33

    This is how I did it. Firstly, add a couple of named scopes to your Post model:

    def previous
      Post.find_by_id(id - 1, :select => 'title, slug etc...')
    end
    
    def next
      Post.find_by_id(id + 1, :select => 'title, slug etc...')
    end
    

    Note the use of the :select option to limit the fields because you probably don't want to retrieve a fully-populated Post instance just for showing the links.

    Then in my posts_helper I have this method:

    def sidebar_navigation_links
      next_post = @post.next
      previous_post = @post.previous
      links = ''
      if previous_post
        links << content_tag(:h3, 'Previous')
        links << content_tag(:ul, content_tag(:li,
                                  content_tag(:a, previous_post.title,
                                              :href => previous_post.permalink)))
      end
      if next_post
        links << content_tag(:h3, 'Next', :class => 'next') if previous_post
        links << content_tag(:h3, 'Next') if previous_post.nil?
        links << content_tag(:ul, content_tag(:li,
                                  content_tag(:a, next_post.title,
                                              :href => next_post.permalink)))
      end
      content_tag(:div, links)
    end
    

    I'm sure this could be refactored to be less verbose, but the intent is clear. Obviously your markup requirements will be different to mine, so you may not choose to use an unordered list, for example.

    The important thing is the use of the if statements because if you're on the first post then they'll be no previous post and conversely, if you're on the last post they'll be no next post.

    Finally, simply call the helper method from your view:

    <%= sidebar_navigation_links %>
    

提交回复
热议问题