没有宝石的Rails分页 [英] Rails Pagination without Gem

查看:69
本文介绍了没有宝石的Rails分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是在不使用gem的情况下为Rails项目创建上一个10",下一个10",最新"和最旧"链接.

I have been tasked to create 'previous 10', 'next 10', 'newest', and 'oldest' links for a Rails project WITHOUT using a gem.

在控制器中,我可以在表中显示10个项目的第一组(最新):

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

但是,我无法正确设置新页面(每页10个),因为我无法更改页码(hxxp://...?page = 1)以获取下一组10.

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:

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
  • 行< ApplicationRecord

看来我应该

  • 行< ActiveRecord :: Base

,但不知道在哪里找到/我应该如何添加它.感谢您耐心等待初学者的问题.

but don't know where to find that/how I should be adding it. Thanks for your patience with the beginner question.

作为参考,erb文件链接格式:

For reference, erb file link format:

<%= link_to 'Next 10', rows_path %>

推荐答案

您所拥有的一切都在正确的轨道上,只是您没有告诉数据库您实际上要检索接下来的10组记录.为此,您需要传递offset,它将告诉DB您要从中检索10条记录的起点".

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

这篇关于没有宝石的Rails分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆