简体   繁体   中英

Rails Pagination without Gem

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:

Any direction is much appreciated. As for the second example site, I have two model classes:

  • ApplicationRecord < ActiveRecord::Base
  • Row < ApplicationRecord

It appears I should be editing:

  • Row < ActiveRecord::Base

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 %>

What you've got there is in the right track, except you're not telling the DB that you actually want to retrieve the next 10 sets of records. To do this, you need to pass the offset , which will tell the DB the "start point" from which you want to retrieve the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM