will_paginate未定义的方法`total_pages'

mik*_*son 61 ruby-on-rails will-paginate

我在这里错过了什么?我正在使用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
>> 
Run Code Online (Sandbox Code Playgroud)

Jir*_*ong 137

试着改变

@locations.paginate(:page => 1, :per_page => 2)
Run Code Online (Sandbox Code Playgroud)

@locations = @locations.paginate(:page => 1, :per_page => 2)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

  • 谢谢Jirapong!你刚解决了我5个小时的问题!提示其他人:如果使用searchlogic,尝试使用search.paginate会抛出错误.在你实际搜索的@whatever对象上使用.paginate方法可能会有所帮助:-) (5认同)
  • 嘎啊!我知道这是一件愚蠢的事情。盯着屏幕看了好久。甜蜜的感谢! (2认同)

小智 29

包括

require 'will_paginate/array' 
Run Code Online (Sandbox Code Playgroud)

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

  • @Lior - 我已经在控制器中添加了这个以及我尝试创建初始化程序,但仍然得到相同的错误 (6认同)

col*_*ain 10

如果其他人有这个问题.在我的情况下,我最后没有在我的控制器方法中调用分页.

示例之前:

@foo = Foo.paginate(:page => params[:page], :per_page => 15)
@foo = Foo.do something
Run Code Online (Sandbox Code Playgroud)

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

@foo = Foo.do something
@foo = Foo.paginate(:page => params[:page], :per_page => 15)
Run Code Online (Sandbox Code Playgroud)


小智 5

@locations = Location.paginate(:all, :conditions => 'city = springfield')
Run Code Online (Sandbox Code Playgroud)

@locations 必须是一个对象

在你的例子中@locations是一个Array

数组不能有total_pages方法