In my Rails 4 app, I have a Post
and a Calendar
model: a calendar
has_many
post
s and a post
belong_to
a calendar
.
In the post
show.html.erb
view, located at /posts/:id
, I want to allow users to navigate back and forth between the posts of the calendar to which the current post belongs to, with a "previous post" button and a "next post" button.
Here are my routes:
resources :calendars do
resources :posts, shallow: true
end
end
I know I will have something like that in my post
show.html.erb
view:
<% if @calendar.posts.count > 1 %>
<%= link_to "< Previous", @previous_post %> | Post Preview | <%= link_to "Next >", @next_post %>
<% else %>
Post Preview
<% end %>
So far, in my PostsController
, I came up with:
def show
@calendar = Calendar.find_by_id(@post.calendar_id)
@posts = @calendar.posts
@previous_post = @post.previous
@next_post = @post.next
end
However, I am struggling to come up with the right definition of the previous
and next
methods (that you can see in the PostsController
code above).
These methods must allow me to find — respectively — the post that is right before or right after the current post in @calendar.posts
How can I achieve that?