Search code examples
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,

    • Change your UI to show problems and activities in separate UIs, then you can paginate them separately
    • Update your models to store both problems and activities in the same table (maybe just a reference table which points to either a Problem or an Activity)
    • If either of these is not feasible, you can consider rolling out a custom solution for the pagination, but it will be tricky.

    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.