【发布时间】:2013-01-17 04:56:18
【问题描述】:
我需要计算评论所在的页面,以便创建指向它的直接链接。我正在使用kaminari 和monogid 进行分页。在kaminari's wiki 上,他们有一个关于如何使用 activerecord 的解决方案,但我不确定将其转换为 mongoid 的最佳方法。
【问题讨论】:
标签: pagination mongoid kaminari mongoid3
我需要计算评论所在的页面,以便创建指向它的直接链接。我正在使用kaminari 和monogid 进行分页。在kaminari's wiki 上,他们有一个关于如何使用 activerecord 的解决方案,但我不确定将其转换为 mongoid 的最佳方法。
【问题讨论】:
标签: pagination mongoid kaminari mongoid3
如果你使用的是 Mongoid 3,这个方法就可以了:
class User
include Mongoid::Document
...
def page_num(options = {})
field = options[:by] || :_id
order = options[:order] || :asc
per = options[:per] || self.class.default_per_page
operator = (order == :asc) ? field.to_sym.lte : field.to_sym.gte
(self.class.where(operator => read_attribute(field)).order_by("#{field} #{order}").count.to_f / per).ceil
end
...
end
希望这会有所帮助。
【讨论】:
这是我最终想出的精简版。
def page_num
number_before = self.class.where(recipe_id: recipe.id).gte(created_at: created_at).count.to_f
number_on_page = self.class.default_per_page
(number_before / number_on_page).ceil
end
【讨论】: