I have been tasked to create 'previous 10', 'next 10', 'newest', and 'oldest' links for a Rails project WITHOUT using a gem.
In the controller, I can show the first (newest) set of 10 items in the table:
...
before_action :set_page, only: [:index]
...
def index
@rows = Row.order(created_at:).limit(10)
end
...
private
def set_page
@page = params[:page] || 0
end
...
However, I don't believe this correctly sets the new pages with 10 each as I am unable to change the page number (hxxp://...?page=1) to get the next set of 10.
I have tried the few pages of instructions I could find including:
Paginate without a gem Next, Previous, buttons for Name.order(:id).limit(10).offset(0)
https://solidfoundationwebdev.com/blog/posts/next-and-previous-links-in-rails
Any direction is much appreciated. As for the second example site, I have two model classes:
It appears I should be editing:
but don't know where to find that/how I should be adding it. Thanks for your patience with the beginner question.
For reference, erb file link format:
<%= link_to 'Next 10', rows_path %>
Pagination which is a really important aspect of any web application help in dividing documents into discrete pages. In Ruby on Rails we can easily paginate data using a gem called 'will_paginate'. The will_paginate library makes adding pagination functionality to Rails apps (and other Ruby frameworks) effortless.
In a Rails application, the paginator (impossible to say out loud without using an Arnold Schwarzenegger voice) makes it very easy to accomplish this. It works with ActiveRecord to divide up the resources in the controller calls and assign a specified amount per page.
Sitechecker.pro, a technical SEO website, defines pagination as “an ordinal numbering of pages, which is usually located at the top or bottom of the site pages.” API pagination just applies that principle to the realm of API design.
What you've got is in the right track except you're not telling the DB that you actually want to retrieve the next 10 records. To do this you need to pass the offset
which tells the DB the "start point" from which you want to retrieve the next 10 records.
You can do this in your code by:
def index
@rows = Row.order(created_at: :desc).limit(10).offset(@page * 10) # This assumes that the page numbering starts from 0 instead of 1 as I gather from the question
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With