如果我有分页项的 ID,我如何找到它的页码?
我正在使用 Rails 3 和 kaminari。
不幸的是,将页码作为参数传递不是一个选项。分页项目是由用户生成的内容随时间演变而维护的图片库的图像。这意味着图像可能会在第一周出现在第一页,但在随后的一周出现在第二页。
另一个选择是维护图像的数字顺序 (acts_as_list),这在我的情况下也是不可能的,因为照片可能出现在不同范围的多个画廊中。
编辑:
我已经为此增加了赏金,因为我看到几年前在不同地方提出过同样的问题,但没有解决方案。如果没有出现事件记录解决方案,我很乐意接受 sql 查询。
最佳答案
# 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
现在你可以把它包装成一个类方法
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
用法
@image.page
@image.page(:created_at)
@image.page(:title, 10)
关于sql - Rails 分页 - 从实例 ID 中查找页码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5422805/