ruby-on-railsrubypaginationwill-paginate

method "where" does not work when switched from will_paginate to pagy gem in rails


My will_paginate code in controller:

@posts = Post.paginate(page: params[:page], per_page: 100).order('created_at DESC')

My pagy code that replaced it:

@pagy, @posts = pagy_countless(Post.order('created_at DESC'), items:5, link_extra: 'class="" style="color:#222222; margin:3px;"')

My view where the problem is:

<% @posts.where(user_id: current_user.friends).each do |post| %>

The error message:

undefined method `where' for #<Array:0x00007f94329d1f70>
Did you mean?  when

What am I doing wrong? The previous will_paginate implementation worked in terms of showing all the posts of user's friends. I'm lost as to what changed in switching to pagy.

UPDATE:

So for the moment, I've solved this by moving the "where..." logic to controller. So:

@pagy, @posts = pagy_countless(Post.where(user_id: current_user.friends).order('created_at DESC'), items:5, link_extra: 'class="" style="color:#222222; margin:3px;"')

And now it works as before. But I'm still confused as to why I had to do this.


Solution

  • Be aware pagy_countless returns an array of items, instead of an ActiveRecord collection. That's why you can't use ActiveRecord methods on @posts (like where).

    Follow my link to see that collection is transformed into array using to_a and then it is returned as second argument of pagy_countless: https://github.com/ddnexus/pagy/blob/bd88866ad6001ae1ef6ce63080d36ecff7bc5603/lib/pagy/extras/countless.rb#L29

    Two comments:
    1. You must use ActiveRecord filters before calling pagy_countless on your collection (eg: where clauses)
    2. If you need to filter records after pagination (which does not make sense in most of the cases), you must use Array methods like select of reject as following @posts.select { |record| record.user.in?(current_user.friends) }