Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the link format in will_paginate for page_cache in Ruby on Rails?

I want to use page_cache with will_paginate.

There are good information on this page below.

http://railsenvy.com/2007/2/28/rails-caching-tutorial#pagination http://railslab.newrelic.com/2009/02/05/episode-5-advanced-page-caching

I wrote routes.rb looks like:

map.connect '/products/page/:page', :controller => 'products', :action => 'index'

But, links of url are not changed to '/products/page/:page' which are in will_paginate helper. They are still 'products?page=2'

How can i change url format is in will_paginate?

like image 612
Jaehyun Avatar asked Feb 28 '23 19:02

Jaehyun


1 Answers

Is that route declared above any RESTful resources routes? That is, your route file should look like the following:

map.connnect '/products/page/:page', :controller => 'products', :action => 'index'
map.resources :products, :except => [:index]

If your routes look correct, you could try monkey-patching the way will_paginate generates the page links. It does so in WillPaginate::ViewHelpers#url_for(page). It's some fairly complex logic in order to handle some tricky edge cases, but you could write a new version that tried the simple version for your products first:

# in lib/cache_paginated_projects.rb
WillPaginate::ViewHelpers.class_eval do
  old_url_for = method(:url_for)
  define_method(:url_for) do |page|
    if @template.params[:controller].to_s == 'products' && @template.params[:action].to_s == 'index'
      @template.url_for :page => page
    else
      old_url_for.bind(self).call(page)
    end
  end
end
like image 165
James A. Rosen Avatar answered Apr 27 '23 16:04

James A. Rosen