我无法继续进行下去。我知道数组没有页面方法,但我该怎么办?
如果在控制台中运行Class.all,则返回#,但如果运行Class.all.page(1),则会出现上述错误。
有什么想法吗?
我无法继续进行下去。我知道数组没有页面方法,但我该怎么办?
如果在控制台中运行Class.all,则返回#,但如果运行Class.all.page(1),则会出现上述错误。
有什么想法吗?
数组没有page方法。
看起来您正在使用kaminari。Class.all返回一个数组,因此无法在其上调用page方法。相反,直接使用Class.page(1)。
对于普通数组,kaminari有一个很好的辅助方法:
Kaminari.paginate_array([1, 2, 3]).page(2).per(1)
Kaminari现在有一个用于分页数组的方法,因此您可以在控制器中执行以下操作:
myarray = Class.all
@results = Kaminari.paginate_array(myarray).page(params[:page])
如果您在使用控制器操作中尝试对模型进行分页,并且使用了kaminari gem时,可能会出现Array未定义方法页面的情况。
NoMethodError at /
undefined method `page' for # Array
提醒自己两件事情,即您想要分页的集合可能是 Array 或 ActiveRecordRelation,或者当然也可能是其他东西。
为了看到区别,假设我们的模型是 Product,我们正在 products_controller.rb 的 index 操作中。 我们可以使用以下方法之一构建我们的 @products:
@products = Product.all
或者
@products = Product.where(title: 'title')
@products = Product.all
@products.class
=> Array
和
@products = Product.where(title: 'title')
@products.class
=> Product::ActiveRecordRelation
@products = Product.where(title: 'title').page(page).per(per)
@products = Kaminari.paginate_array(Product.all).page(page).per(per)
简单概括一下,将分页功能添加到你的模型中的好方法:
def index
page = params[:page] || 1
per = params[:per] || Product::PAGINATION_OPTIONS.first
@products = Product.paginate_array(Product.all).page(page).per(per)
respond_to do |format|
format.html
end
end
在需要分页的模型中(product.rb):
并且在模型内部:paginates_per 5
# Constants
PAGINATION_OPTIONS = [5, 10, 15, 20]
Kaminari::Hooks.init
我在另一个答案中发布了更多细节:
undefined method page for #<Array:0xc347540> kaminari "page" error. rails_admin
我遇到了同样的错误。执行了bundle update,然后重启了服务器。两者中的一个解决了问题。