ruby-on-railsrubypagination

Using combined models with pagy, getting undefined method 'offset' error


I am using pagy. I combined two models into one, and I used pagy on that combined model. I am getting this error:

undefined method `offset' for #<Array:0x00007f886f88b3b0>

With the last line of the code below highlighted.

My code:

@problems = Problem.me_and_friends(current_user)
@activities = Activity.me_and_friends(current_user)
@combine = (@problems + @activities).sort{|a,b| a.created_at <=> b.created_at }
@pagy, @combined = pagy_countless(@combine, items:100, link_extra: 'class="" style="color:black; margin:3px;"')

It worked fine with using pagination on @problems alone.

I'd appreciate any help.


Solution

  • As soon as you call the (@problems + @activities), you transform the ActiveRecord::Relation into an array (which is also not good because you are loading all the database rows into memory, sorting and then paginating them). Pagy expects an ActiveRecord::Relation to work, hence the error.

    You can consider multiple solutions,


    Update: June 21, 2021

    If you are using Rails 6, it introduces the concept of Delegated Types which fits well into this scenario. The example given in the link mentions the issue of pagination across different tables.