使用 kaminari 查找给定记录的页面 [英] find page for given record using kaminari

查看:43
本文介绍了使用 kaminari 查找给定记录的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby on Rails 3 项目.更新记录后,我们返回所有记录的索引(不是更新记录的视图).该索引使用 Kaminari 进行分页.我们如何返回包含更新记录的索引页面?

Ruby on Rails 3 project. After updating a record we return to the index of all records (not a view of the updated record). The index is paged with Kaminari. How do we return to the page of the index that contains the updated record?

推荐答案

Java JPA/Hibernate 有一个类似的问答 使用JPA(Hibernate)找出包含给定记录的页面,它显示了获取记录偏移量所需的sql索引视图.类似的东西

There is a similar question and answer for Java JPA/Hibernate Finding out the page containing a given record using JPA (Hibernate) that shows the sql needed to get the offset of the record in the index view. Something like

SELECT COUNT(*)
FROM Model r
WHERE r.column < ?
ORDER BY r.id

页码为 offset/records_per_page + 1.

The page number will be offset/records_per_page + 1.

那么问题是如何从 Kaminari 获取records_per_page?Kaminari 允许您在配置中设置每页的记录数,并通过 Model.paginates_per 为特定模型设置记录数.它提供了 Model.default_per_page 方法来为模型生成每页的记录数.

The question then is how to get the records_per_page from Kaminari? Kaminari lets you set the number of records per page in configuration, and for a specific model through Model.paginates_per. It provides the Model.default_per_page method to yield number of records per page for the model.

决定页面的最佳位置是显示索引的控制器方法.该方法已经获取页面参数(如果存在)以显示正确的页面.另一种方法是在重定向之前计算页面并发送页面参数.让我们试试前者.

The best place to decide the page will be in the controller method that displays the index. That method already picks up the page param, if present, to display the correct page. Another way would be to compute the page before redirect and send the page param. Let's try the former.

保存编辑后,我们使用一个参数重定向到索引,该参数标识了我们想要包含在索引页面中的记录使用参数重定向.索引按 Model.column 排序.

After saving the edit we redirect to the index with a param identifying the record we want included in the index page redirect with params. The index sorts by Model.column.

redirect_to model_index_url(:for_column => @model_record.column), 
   :notice => 'Record saved'

然后在控制器的 index 方法中,我们让页面参数管理,或者从 for_column 参数计算页面(如果存在).

Then in the index method of the controller we let the page param govern, or compute the page from the for_column param if present.

page = 1 
if (params[:page])
  page = params[:page]
elsif (params[:for_column])
  offset = Model.select('count(*) as count').where('? < column',
     params[:for_column]).order(id).first
  page = offset.count/Model.default_per_page + 1
end
@records = Model.all.order('column desc').page(page)

当然,Model 和 Model.column 代表您的应用程序的模型和列名称.

And of course, Model and Model.column stand for the model and column name for your application.

这篇关于使用 kaminari 查找给定记录的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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