Question

I would like to know if someone could spare some light on this

i'm using the acts_as_follower with will_paginate

Controller

@products = current_user.following_shops.includes(:products).collect{|u| u.products.paginate(:page => params[:page]).order("created_at DESC")}.flatten

view

    <table>
      <% @products.each do |p| %>
            <tr>
              <td>
                <%= image_tag p.shop.logo.url(:thumb_feed).to_s %>
              </td>


              <td>
            <%= link_to(image_tag(p.f1.url(:table).to_s), product_path(p.id)) %>      
            <%= link_to p.name,  product_path(p.id)%>

                          </td>

    </tr>


  <% end %>


         </table>

<%= will_paginate(@products) %>

but rails keep spit this error:

undefined method `total_pages' for

Was it helpful?

Solution

The #paginate method creates a decorated WillPaginate collection, which includes the information needed to page through the results. You're just creating an array by collecting WillPaginate arrays and flattening them into a normal array, so they won't have all the necessary decoration to do the pagination. The quick, dirty, and wrong answer here is to take your products array, and wrap it as a paginated collection:

@products = WillPaginate::Collection.create(current_page, per_page, @products.length) do |pager|
  pager.replace @products
end

You're doing a rather unorthodox operation here, and it's going to be pretty inefficient; it looks like you want to get all products in all the shops for a given user, and page through them, right? If that's the case, you probably want to take a different approach.

First, set up a has_many :through association to get to those products through your followed shops association (this syntax may need some work; my ActiveRecord is rusty):

class User
  has_many :following_products, through: :following_shops, class_name: "Product"
end

Then paginate that association:

current_user.following_products.order("created_at DESC").paginate(page: params[:page])

This prevents you from having to select and iterate the entire list of shops for every page, paginates cleanly, and is much more expressive.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top