2016-06-22 75 views
0

我有一個來自Active Record的來自我的模型的集合數組。NoMethodError - 未定義的方法`total_pages'for#<Array:0x007fdd28be0430>:

@ad_groups = AdGroup.where(is_template: false).paginate(:page => params[:page]).order(:id).reverse 

然後在我的模型予有

self.per_page = 25 
WillPaginate.per_page = 25 

在我的視圖索引

= will_paginate @ad_groups 

以及所需的will_paginate /陣列。我看到有人在初始化程序中使用此代碼

require 'will_paginate/collection' 

class Array 
    # Paginates a static array (extracting a subset of it). The result is a 
    # WillPaginate::Collection instance, which is an array with a few more 
    # properties about its paginated state. 
    # 
    # Parameters: 
    # * <tt>:page</tt> - current page, defaults to 1 
    # * <tt>:per_page</tt> - limit of items per page, defaults to 30 
    # * <tt>:total_entries</tt> - total number of items in the array, defaults to 
    # <tt>array.length</tt> (obviously) 
    # 
    # Example: 
    # arr = ['a', 'b', 'c', 'd', 'e'] 
    # paged = arr.paginate(:per_page => 2)  #-> ['a', 'b'] 
    # paged.total_entries      #-> 5 
    # arr.paginate(:page => 2, :per_page => 2) #-> ['c', 'd'] 
    # arr.paginate(:page => 3, :per_page => 2) #-> ['e'] 
    # 
    # This method was originally {suggested by Desi 
    # McAdam}[http://www.desimcadam.com/archives/8] and later proved to be the 
    # most useful method of will_paginate library. 
    def paginate(options = {}) 
    page  = options[:page] || 1 
    per_page = options[:per_page] || WillPaginate.per_page 
    total = options[:total_entries] || self.length 

    WillPaginate::Collection.create(page, per_page, total) do |pager| 
     pager.replace self[pager.offset, pager.per_page].to_a 
    end 
    end 
end 

沒有工作。任何想法我做錯了什麼?

回答

2

這是因爲您在查詢結束時有.reverse。此方法將返回一組模型,而不是ActiveRecord::Relation。只需將您需要的訂單添加到您的.order()方法中:

@ad_groups = AdGroup.where(is_template: false) 
       .paginate(:page => params[:page]).order('id DESC') 
#            HERE ======= | 
+0

謝謝!有效 –

相關問題