user2492854
user2492854

Reputation: 401

Pagination in Rails: undefined method `total_pages' for []:Array

In my Rails application I need to perform search based on some conditions. Since I have millions of records I need to perform pagination. I tried will_paginate. The output I am getting is "undefined method `total_pages' for []:Array"

My controller:

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

My view:

<%= 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>

I tried using will_paginate, but it is not working. The error I am getting is "undefined method `total_pages' for []:Array". What did I do wrong?

Upvotes: 0

Views: 3055

Answers (1)

mihai
mihai

Reputation: 38593

@tweets is an array, and will_paginate doesn't work with arrays by default. To enable this behavior, add a new file in config/initalizers with this line:

require 'will_paginate/array'

Upvotes: 3

Related Questions