find page for given record using kaminari

前提是你 提交于 2019-12-04 13:13:10
Douglas Lovell

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

The page number will be offset/records_per_page + 1.

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.

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'

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)

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

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