Rails Pagination - find page number from instance id
In the case where I have the id of a paginated item, how can I find its page number?
I'm using rails 3 and kaminari.
Unfortunately passing the page number as a parameter is not an option. The paginated items are images of an image gallery maintained by user generated content evolving over time. This means an image may appear on page one on week one but page 2 a subsequent week.
Another option would have been maintaining a numeric order of images (acts开发者_运维问答_as_list), again this is not possible in my case as photos may appear in multiple galleries of varying scopes.
edit:
Have added a bounty to this as I see this same question asked years ago in various places with no solution. I'm happy to accept an sql query if no active record solution comes up.
# Your "per_page" count
per_page = 30
# Your Image instance:
@image = Image.find_your_image
# SQL. If you're ordering by id, how many lower IDs are there?
position = Image.where("id <= ?", @image.id").count
# Your page
page = (position.to_f/per_page).ceil
Now you can wrap it as a class method
class Image < ActiveRecord::Base
def page(order = :id, per_page = 30)
position = Image.where("#{order} <= ?", self.send(order)).count
(position.to_f/per_page).ceil
end
end
Usage
@image.page
@image.page(:created_at)
@image.page(:title, 10)
If you find the page id means it will need the some sql queries. instead of that you can pass the page value as a param. This will increase your performance too.
I had the same issue but with but with multiple orders. I only could get it working with a little bad trick.
@model = Model.find(params[:id])
page = 1
if params[:page]
page = params[:page]
else
page = (Model.some_scope.order(some_attribute: :desc, updated_at: :desc).pluck(:id).index(@model.id).to_f / per_page).ceil
end
It only works good if you don't have to many records in the result of the pluck, otherwise it will get slow.
精彩评论