简体   繁体   English

没有宝石的导轨分页

[英]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. 我的任务是为没有使用gem的Rails项目创建“前10个”,“下10个”,“最新”和“最旧”的链接。

In the controller, I can show the first (newest) set of 10 items in the table: 在控制器中,我可以在表格中显示第一组(最新的)10项:

...
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. 但是,我不相信这会正确地设置10个新页面,因为我无法更改页码(hxxp:// ...?page = 1)以获得下一组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 ApplicationRecord <ActiveRecord :: Base
  • Row < ApplicationRecord 行<ApplicationRecord

It appears I should be editing: 看来我应该编辑:

  • Row < ActiveRecord::Base 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: 供参考,erb文件链接格式:

<%= 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. 你在那里得到的是正确的轨道,除了你没有告诉数据库你真的想要检索接下来的10组记录。 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. 为此,您需要传递offset ,该offset将告诉DB您要从中检索10条记录的“起始点”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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