[英]Rails Pagination without Gem
我的任務是為沒有使用gem的Rails項目創建“前10個”,“下10個”,“最新”和“最舊”的鏈接。
在控制器中,我可以在表格中顯示第一組(最新的)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
...
但是,我不相信這會正確地設置10個新頁面,因為我無法更改頁碼(hxxp:// ...?page = 1)以獲得下一組10。
我已經嘗試了幾頁我可以找到的說明,包括:
沒有寶石的Paginate Next,Previous,Name.order(:id).limit(10).offset(0)的按鈕
https://solidfoundationwebdev.com/blog/posts/next-and-previous-links-in-rails
任何方向都非常感謝。 至於第二個示例站點,我有兩個模型類:
看來我應該編輯:
但不知道在哪里找到/我應該如何添加它。 感謝您對初學者問題的耐心。
供參考,erb文件鏈接格式:
<%= link_to 'Next 10', rows_path %>
你在那里得到的是正確的軌道,除了你沒有告訴數據庫你真的想要檢索接下來的10組記錄。 為此,您需要傳遞offset
,該offset
將告訴DB您要從中檢索10條記錄的“起始點”。
您可以在代碼中執行以下操作:
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.