63

我在这里想念什么?我正在使用 haml_scaffold 生成器,并且页面可以与 will_paginate 一起正常工作。当我开始修修补补时,我最终得到了这个“total_pages”错误,我不确定我在做什么导致它。任何人有任何见解?我正在使用 mislav-will_paginate 2.3.11。

mike@jauntyjackalope:~/project$ script/console
Loading development environment (Rails 2.3.4)
>> @locations = Location.find_all_by_city("springfield")
=> [#<Location id: 3, address: "123 Main St", city: "springfield", phone: "321-1234", business_id: 2>]
>> @locations.class
=> Array
>> @locations.collect{|loc| loc.business}
=> [#<Business id: 2, name: "A Bar", website: "www.abar.com", business_owner_id: 1, created_at: "2009-08-31 21:13:10", updated_at: "2009-08-31 21:13:10">]
>> @locations.class
=> Array
>> @locations.paginate(:page => 1, :per_page => 2)
=> [#<Location id: 3, address: "123 Main St", city: "springfield", phone: "321-1234", business_id: 2>]
>> helper.will_paginate(@locations)
NoMethodError: undefined method `total_pages' for #<Array:0xb6f83bc4>
 from /var/lib/gems/1.8/gems/mislav-will_paginate-2.3.11/lib/will_paginate/view_helpers.rb:197:in `total_pages_for_collection'
 from /var/lib/gems/1.8/gems/mislav-will_paginate-2.3.11/lib/will_paginate/view_helpers.rb:98:in `will_paginate'
 from (irb):7

>> y @locations
--- 
- !ruby/object:Location 
  attributes: 
    city: springfield
    business_id: "2"
    id: "3"
    phone: 321-1234
    address: 123 Main St
  attributes_cache: {}

  business: !ruby/object:Business 
    attributes: 
      name: A Bar
      updated_at: 2009-08-31 21:13:10
      website: www.abar.com
      id: "2"
      created_at: 2009-08-31 21:13:10
      business_owner_id: "1"
    attributes_cache: {}

=> nil
>> 
4

5 回答 5

142

尝试改变

@locations.paginate(:page => 1, :per_page => 2)

@locations = @locations.paginate(:page => 1, :per_page => 2)

希望这可以帮助

于 2009-09-11T06:11:45.340 回答
29

包括

require 'will_paginate/array' 

在加载该代码之前将解决您的问题。

于 2011-11-03T11:46:51.840 回答
11

如果其他人有这个问题。就我而言,我没有最后在我的控制器方法中调用分页。

之前的例子:

@foo = Foo.paginate(:page => params[:page], :per_page => 15)
@foo = Foo.do something

之后的示例: 我在方法中最后调用了分页,因为 rails 从上到下读取并且它似乎修复了我的错误。

@foo = Foo.do something
@foo = Foo.paginate(:page => params[:page], :per_page => 15)
于 2013-07-21T18:32:39.800 回答
5
@locations = Location.paginate(:all, :conditions => 'city = springfield')

@locations必须是一个对象

在您的示例@locations中是Array

数组不能有 total_pages 方法

于 2010-11-23T13:25:51.180 回答
1

I was encountering a similar a error undefined method 'total_pages' for ActiveRecord_AssociationRelation.

It turns out that renaming my variable solved the issue.

Here was my code:

@reviews = @user.reviews.paginate(page: params[:page], per_page: 5).order('created_at DESC')

I changed it to this:

@user_reviews = @user.reviews.paginate(page: params[:page], per_page: 5).order('created_at DESC')

And it solved the issue. It's very bizarre but it there may have been some kind of conflict.

Since I spent a few hours researching, I thought it might help someone one day as well!

于 2020-07-19T07:52:11.510 回答