stonep
stonep

Reputation: 309

How do I create will_paginate links to other pages?

I am trying to do pagination for products. I have:

   # Routes
    match 'dashboard' => 'dashboard#index'

   # Dashboard Controller
   def index 
    @products = Product.order("id").page(params[:page]).per_page(4)
   end

   # Dashboard Index View
   h1 products
   .products
   = render @products
   = will_paginate(@products)

The pagination links are showing up in the dashboard index view.

Example

     <-- previous 1 2 3 next -->

But the links don't append the proper path. The default view is localhost:3000/dashboard.
The pagination links have:

     http://localhost:3000/?page=2

For testing, if I just enter the proper path with the page params in the url bar

     http://localhost:3000/dashboard?page=2

it works fine and paginates, displaying the next set of products. My goal is to have the links have dashboard in the link. I am guessing this will happen with some combination of passing options in the "will_paginate" method in the view.

I want this to happen when the user is at their root page:

  http://localhost:3000/dashboard

Upvotes: 3

Views: 2708

Answers (2)

lethang7794
lethang7794

Reputation: 231

For anyone who still has this problem:

# View
# Generating pagination links for collection in another controller/action.
will_paginate @products, params: { controller: 'dashboard', action: 'index' } 

and:

# routes.rb
get 'dashboard', to: 'dashboard#index' # Before root, 2 route to the same action, Rails/will_paginate will use the first matched one in routes.rb.
root 'dashboard#index'

Upvotes: 0

Muntasim
Muntasim

Reputation: 6786

To override the will_paginate url:

will_paginate(@products, :params => { :controller => "dashboard", :action => "index" })

Or if you have named route for dashboard:

will_paginate(@products, :params => { :controller => dashboard_path })

will paginate documentation

Upvotes: 6

Related Questions