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!
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!
My method will allow you to automatically use model scopes. For example, you may only want to display posts that are "published."
In your model:
In your view
In your controller
Associated RSpec tests:
Note: there will be small issues when you reach the first/last post in a collection. I recommend a view helper to conditionally show the previous or next button only if it exists.
Give the will_paginate Gem a try. It provides all the features you need to paginate your post entries. learn here too
You can look at here too for example code if you want add next and previous buttons.
I've created gem
proximal_records
especially for this kind of task and it works on any dynamically created scope in your model.https://github.com/dmitry/proximal_records
Basic example:
If each title is unique and you need alphabetical, try this in your
Post
model.You can then link to those in the view.
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.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:
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.
This is how I did it. Firstly, add a couple of named scopes to your
Post
model:Note the use of the
:select
option to limit the fields because you probably don't want to retrieve a fully-populatedPost
instance just for showing the links.Then in my
posts_helper
I have this method: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: