【问题标题】:Pagination in Rails: undefined method `total_pages' for []:ArrayRails 中的分页:[]:Array 的未定义方法“total_pages”
【发布时间】:2013-08-20 22:14:32
【问题描述】:

在我的 Rails 应用程序中,我需要根据某些条件执行搜索。由于我有数百万条记录,我需要执行分页。我试过 will_paginate。我得到的输出是“[]:Array 的未定义方法 `total_pages'”

我的控制器:

class TweetsController<ApplicationController
  def index
    city = params[:show]
    search_term = params[:text]        

    search_term.gsub!(/\s/, '%')
    city_coordinates = Coordinates.where('city=?', city)

    @tweets = if (city_coordinates.count == 1 && city_coordinates.first.valid_location?)
      @tweets = Tweets.for_coordinates(city_coordinates.first).paginate(page: params[:page], per_page: 50) &  Tweets.where("tweet_text LIKE?" , "%#{search_term}%").paginate(page: params[:page], per_page: 50)
    else if (city_coordinates.count != 1 )
      @tweets = Tweets.for_user_location(city).paginate(page: params[:page], per_page: 50) &  Tweets.where("tweet_text LIKE?" , "%#{search_term}%").paginate(page: params[:page], per_page: 50)
    else
      @tweets = Tweets.where("tweet_text LIKE? ", "%#{search_term}%").paginate(page: params[:page], per_page: 50)
    end
    end
  end
end

我的看法:

<%= will_paginate @tweets %>
<% @tweets.each do |tweets| %>
<ul>
  <li><%= tweets.id %></li>
  <li><%= tweets.tweet_created_at %></li>    
  <li><%= tweets.tweet_source %></li>
  <li><%= tweets.tweet_text %></li>
  <li><%= tweets.user_id %></li>
  <li><%= tweets.user_name %></li>
  <li><%= tweets.user_sc_name %></li>
  <li><%= tweets.user_loc %></li>
  <li><%= tweets.user_img %></li>
  <li><%= tweets.longitude %></li>
  <li><%= tweets.latitude %></li>
  <li><%= tweets.place %></li>
  <li><%= tweets.country %></li>
<% end %>
</ul>

我尝试使用 will_paginate,但它不起作用。我得到的错误是“[]:Array 的未定义方法 `total_pages'”。我做错了什么?

【问题讨论】:

  • 这个错误发生在哪里?
  • 它在代码中显示第 1 行 view ,但我认为那里没有错误
  • 另外,请发布您的实际代码。您在此处发布的内容包含许多错误。
  • 这是我的实际代码,它在没有分页的情况下可以正常工作,但是分页我得到了这个错误
  • 您的问题可能是因为您使用&amp; 将两个集合连接在一起,将其转换为数组而不是 will_paginate 集合。如果你不这样做,试试它是否有效。

标签: ruby-on-rails ruby


【解决方案1】:

@tweets 是一个数组,默认情况下will_paginate 不适用于数组。要启用此行为,请使用以下行在 config/initalizers 中添加一个新文件:

require 'will_paginate/array'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 2010-11-27
    • 2013-10-12
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多