1
我需要計算哪些頁面上有評論,所以我可以創建一個直接鏈接到它。我使用kaminari與monogid分頁。在kaminari's wiki他們有一個關於如何使用activerecord做的解決方案,但我不確定將其轉換爲mongoid的最佳方法。使用kaminari和mongoid來計算模型所在的頁面是什麼
我需要計算哪些頁面上有評論,所以我可以創建一個直接鏈接到它。我使用kaminari與monogid分頁。在kaminari's wiki他們有一個關於如何使用activerecord做的解決方案,但我不確定將其轉換爲mongoid的最佳方法。使用kaminari和mongoid來計算模型所在的頁面是什麼
這是一個精簡版,我最終提出了。
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
如果使用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
希望這有助於。