ruby-on-rails will_paginate未定义的方法'total_pages'

sd2nnvve  于 2022-12-24  发布在  Ruby
关注(0)|答案(5)|浏览(117)

这里我遗漏了什么?我使用的是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
>>
ddhy6vgd

ddhy6vgd1#

试着改变

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

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

whitzsjs2#

包括

require 'will_paginate/array'

在加载代码之前就能解决问题。

vfh0ocws

vfh0ocws3#

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

之前的示例:

@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)
igetnqfo

igetnqfo4#

@locations = Location.paginate(:all, :conditions => 'city = springfield')

@locations必须是对象
在您示例中,@locationsArray
数组不能有total_pages方法

c3frrgcw

c3frrgcw5#

我遇到了类似的错误undefined method 'total_pages' for ActiveRecord_AssociationRelation
事实证明,重命名我的变量解决了这个问题。
下面是我的代码:

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

我把它改成了:

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

它解决了这个问题。这很奇怪,但它可能有某种冲突。
由于我花了几个小时的研究,我想它可能有一天也会帮助别人!

相关问题