Reputation: 13
I need to make a next/prev button for a page that is listing posts (without gem). I want to limit it to 8 per page (newest to oldest). For the controller I have this:
def index
@links = Link.order(created_at: :desc).limit(8).offset(@page * 8)
end
private
def set_page
@page = params[:page] || 0
end
In the index.html.erb
<%= link_to 'Prev Page', page: -1.to_i %>
<%= link_to 'Next Page', page: +1.to_i %>
It listed 8 topics on the first page but when I click next page, its just a blank page. I followed this from another post but I'm not sure what I missed. Thanks
Upvotes: 1
Views: 494
Reputation: 7777
Look, if you don't want use gem then follow the following code like in the controller
before_action :set_page, only: [:index]
PAGE_SIZE = 8
def index
@links = Link.order(created_at: :desc).offset(PAGE_SIZE * @page).limit(PAGE_SIZE)
end
private
def set_page
@page = (params[:page] || 0).to_i
end
and in the view
<nav>
<ul class="pager">
<li class="previous <%= page == 0 ? 'disabled' : '' %>">
<%= link_to_if page > 0, "← Previous".html_safe, your_index_path(page: page - 1) %>
</li>
<li class="next">
<%= link_to "Next →".html_safe, your_index_path(page: page + 1) %>
</li>
</ul>
</nav>
Upvotes: 3