Rails 3:#<Array:0xafd0660>没有定义“page”方法

29

我无法继续进行下去。我知道数组没有页面方法,但我该怎么办?

如果在控制台中运行Class.all,则返回#,但如果运行Class.all.page(1),则会出现上述错误。

有什么想法吗?


注意:在Rails 3中,Model.all返回记录数组,导致此问题。在Rails 4+中,Model.all返回ActiveRecord :: Relation,您确实可以将kaminari作用域、页面和per链接到其中。[Rails发布说明] (https://guides.rubyonrails.org/4_0_release_notes.html#active-record-notable-changes) - notapatch
5个回答

44

数组没有page方法。

看起来您正在使用kaminari。Class.all返回一个数组,因此无法在其上调用page方法。相反,直接使用Class.page(1)。

对于普通数组,kaminari有一个很好的辅助方法:

Kaminari.paginate_array([1, 2, 3]).page(2).per(1)

12

Kaminari现在有一个用于分页数组的方法,因此您可以在控制器中执行以下操作:

myarray = Class.all
@results = Kaminari.paginate_array(myarray).page(params[:page])

我在Kaminari模块中遇到了“paginate_array”未定义的方法,该如何解决? - Þaw
@Þaw 看起来你在使用较旧版本的Kaminari。 - DaveStephens

5

如果您在使用控制器操作中尝试对模型进行分页,并且使用了kaminari gem时,可能会出现Array未定义方法页面的情况。

NoMethodError at /
undefined method `page' for # Array

提醒自己两件事情,即您想要分页的集合可能是 ArrayActiveRecordRelation,或者当然也可能是其他东西。

为了看到区别,假设我们的模型是 Product,我们正在 products_controller.rbindex 操作中。 我们可以使用以下方法之一构建我们的 @products

@products = Product.all

或者

@products = Product.where(title: 'title')

无论哪种方式,我们都能获得您的产品,但类别是不同的。
@products = Product.all
@products.class
=> Array

@products = Product.where(title: 'title')
@products.class
=> Product::ActiveRecordRelation

因此,根据集合的类别,我们希望对Kaminari进行分页,提供以下内容:
@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]

1

0

我遇到了同样的错误。执行了bundle update,然后重启了服务器。两者中的一个解决了问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接