0

I have a question about paginating non-persisted data which is sourced from a remote http request to an API (or many).

My Rails 3 app sends a net/http request to a search engine API and receives a JSON object. I'm loading this into ruby and paginating the results in the view. The initial query receives 50 hits and Kaminari is displaying:

@items = Kaminari.paginate_array(array).page(params[:page]).per(10)

Now when I click for page 2 in the view, the controller executes the request for the JSON again rather than using the results in array.

This code is in a helper method and that's a problem. I that realise moving the pagination code into the controller will make this possible. bing_search returns @items now.

if params[:bing]
  @bing = bing_search(@query)
end

I need something like:

@items = Kaminari.paginate_array(@bing).page(params[:page]).per(10)

I am just wondering how I can persist the array while paginating. I have just looked at caching and that looks promising but I don't know anything about how it works yet.

Cœur
  • 37,241
  • 25
  • 195
  • 267
iNulty
  • 923
  • 8
  • 17
  • You'll need to store it somewhere. Remember, rails is no different than any other server side language. It will not hold on to variables that are just set in memory. You either need to use a data store of some kind, or throw it into a session. Is there a reason you can't throw it into a db and clean it up later via a cron job? – agmcleod Jul 10 '12 at 03:22
  • @agmcleod: yeah, I'll need to persist it somewhere. would a session variable handle this? I could create a session variable to store the results and overwrite it when a new search is made? – iNulty Jul 10 '12 at 10:59
  • Yep, you can store objects in a session, but it's usually best not to. Use the session object in the controller like you would any other hash. `session[:some_key] = array` – agmcleod Jul 10 '12 at 21:39
  • Thanks agmcleod but I've decided to go with the db. I am going to use the session_id as one of the columns though. that way i can retreive multiple searches of a single session. I've run into more trouble here though :P http://stackoverflow.com/questions/11422494/storing-complex-records-in-rails-database-with-form-tag – iNulty Jul 10 '12 at 22:50

0 Answers0