Rails Pagination without Gem

浪尽此生 提交于 2020-01-13 10:44:29

问题


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:

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

回答1:


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


来源:https://stackoverflow.com/questions/42708028/rails-pagination-without-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!