Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 689
mark Avatar asked Mar 24 '11 17:03

mark


1 Answers

# 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)
like image 96
fl00r Avatar answered Nov 11 '22 16:11

fl00r