Rails Pagination - find page number from instance id Rails Pagination - find page number from instance id sql sql

Rails Pagination - find page number from instance id


# Your "per_page" countper_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 pagepage = (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  endend

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).ceilend

It only works good if you don't have to many records in the result of the pluck, otherwise it will get slow.