user984621
user984621

Reputation: 48443

Rails will_paginate - how to make nicer route?

I have on the homepage list of articles that are listed with using will_paginate gem. Everything works well, but there is one thing I would want to improve - on the homepage, the data are loaded into home controller and index action.

So, when I load my website - www.website.com, data are loaded into home/index. When I click on the pagination link for the second page, the link is www.website.com/home/index?page=2. I would like to see there in the best way www.website.com/page/2 (or www.website.com/?page=2).

Basically, the point is to remove from the URL /home/index - is there any way to do this?

Thanks

Upvotes: 1

Views: 314

Answers (2)

Tala
Tala

Reputation: 8928

Try this

root to: 'home#index'

in you config/routes.rb file

EDIT

to be able to route these kind of requests: www.website.com/page/2

add this to routes.rb:

match "page/:page" => "your_root_controller#index"

this way :page will be in your params hash. and for example index method to view your Message model can be:

  def index
    @messages = Messages.paginate(page: params[:page])
  end

hope that can help. for more information please refer to RoR routing

Upvotes: 0

trushkevich
trushkevich

Reputation: 2677

You may do it this way - add this class to some helper module, for example app/helpers/application_helper.rb:

module ApplicationHelper

  class SmartLinkRenderer < WillPaginate::ActionView::LinkRenderer
    protected
    def link(text, target, attributes = {})
      if target.is_a? Fixnum
        attributes[:rel] = rel_value(target)
        target = url(target)
      end
      attributes[:href] = target.gsub(/[?&]page=(\d+)/,'/page/\1')
      tag(:a, text, attributes)
    end
  end

end

You may customize it according to your needs, for example do

attributes[:href] = target.gsub(/home\/index/,'')

or whatever. And then you may do this in your views:

<%= will_paginate @items, :renderer => 'ApplicationHelper::SmartLinkRenderer' %>

Upvotes: 1

Related Questions