【问题标题】:Calculate what page a model is on using kaminari and mongoid使用 kaminari 和 mongoid 计算模型所在的页面
【发布时间】:2013-01-17 04:56:18
【问题描述】:

我需要计算评论所在的页面,以便创建指向它的直接链接。我正在使用kaminarimonogid 进行分页。在kaminari's wiki 上,他们有一个关于如何使用 activerecord 的解决方案,但我不确定将其转换为 mongoid 的最佳方法。

【问题讨论】:

    标签: pagination mongoid kaminari mongoid3


    【解决方案1】:

    如果你使用的是 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
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      这是我最终想出的精简版。

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-26
        • 2016-09-21
        • 1970-01-01
        • 2011-09-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多