Rails分页 - 从实例ID中查找页码

mar*_*ark 15 sql database pagination ruby-on-rails ruby-on-rails-3

如果我有一个分页项的ID,我怎么能找到它的页码?

我正在使用rails 3和kaminari.

不幸的是,将页码作为参数传递不是一种选择.分页项是由用户生成的内容随时间演变而维护的图像库的图像.这意味着图像可能会出现在第一周的第一页上,而后一周则出现在第二页上.

另一种选择是保持图像的数字顺序(acts_as_list),在我的情况下这是不可能的,因为照片可能出现在不同范围的多个画廊中.

编辑:

为此我添加了一笔赏金,因为我看到几年前在不同地方提出的同样问题没有解决方案.如果没有活动记录解决方案,我很乐意接受SQL查询.

fl0*_*00r 20

# 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
Run Code Online (Sandbox Code Playgroud)

现在您可以将其包装为类方法

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
Run Code Online (Sandbox Code Playgroud)

用法

@image.page
@image.page(:created_at)
@image.page(:title, 10)
Run Code Online (Sandbox Code Playgroud)