4

I have a model that connects to an external database and I query using the find_by_sql method like so:

External.find_by_sql("SELECT * from table")

However when I add the .page(params[:page]), the error "undefined method page for class array" appears. Is it possible to paginate the results fetched using find_by_sql?

chourobin
  • 4,004
  • 4
  • 35
  • 48

3 Answers3

10

This worked for me:

Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

https://github.com/kaminari/kaminari/wiki/Kaminari-recipes#-how-do-i-paginate-an-array

Jenn
  • 3,143
  • 1
  • 24
  • 28
  • 1
    This is great if you know your array will never be too large. Otherwise, you still load all the objects into memory, I believe. – reid Jun 06 '18 at 15:13
2

If you cannot avoid using find_by_sql, check out last question of kaminari wiki.

methyl
  • 3,272
  • 2
  • 25
  • 34
  • 1
    The last item in the wiki is: Using Kaminari with InheritedResources. I don't see anything in the wiki about `find_by_sql`. – stephen.hanson Sep 05 '18 at 20:10
  • 1
    It was probably this one: https://github.com/kaminari/kaminari/wiki/Kaminari-recipes/e114c562b3b9a4896ad2d3db10e56eadf5d213dd#-how-to-paginate-an-array-i-need-page-and-per-for-array-class or the one after – methyl Sep 22 '18 at 16:06
0

Looking at the kaminari plugin it seems to only apply to ActiveRecord and ActiveRecord scopes, but find_by_sql does not work as a scope, but rather returns an Array.

I haven't found, digging through kaminari, a transparent way to 'paginate' an array. You could try to roll it by hand, but it might be tricky.

Thomas Andrews
  • 1,577
  • 1
  • 13
  • 31