rails 3 : will paginate creating incorrect links

2019-09-05 14:27发布

问题:

This is my route

match "/search/*keywords" => "public/search#index" ,:method=>:get,    :as=>:search_with_keywords    

an example could be "/search/country-india/product_type-mobilephones"

am using will paginate to create pagination links
the */keywords is causing the following problem while creating the pagination link

<%= will_paginate @results, :container => false, :class => 'pagination ajax' %>  

the generated link is "http://localhost:3000/search?keywords=country-india%2Fproduct_type-mobilephones&lang=en&page=2"

what i want is "http://localhost:3000/search/country-india/product_type-mobilephones?lang=en&page=2"

how can i achieve this ...

回答1:

If you're using the Rails 3 version of Will Paginate (currently "3.0.pre2") then you can use the :renderer option and customize how the links are generated.

So first, if you're not up-to-date then you can follow the installation instructions and usage instructions from the will paginate wiki.

Then in lib you can create your own renderer that overwrites the link generation, perhaps something like

class SearchLinkRenderer < WillPaginate::ViewHelpers::LinkRenderer

  protected

  def url(page)

    @base_url_params ||= begin
      url_params = base_url_params
      merge_optional_params(url_params)
      url_params
    end

    url_params = @base_url_params.dup
    add_current_page_param(url_params, page)

    @template.search_with_keywords_url(url_params)
  end
end

and then call it with

<%= will_paginate @results, :container => false, :class => 'pagination ajax', :renderer => SearchLinkRenderer %>

The default renderer uses

@template.url_for(url_params)

which is what is "messing up" your links. You can use any path from @template, so

@template.search_with_keywords_url(url_params)

should do the trick. Now if you call will_paginate with your own renderer, it should pass use your path instead of url_for, and the parameters should match up nicely. If they don't then check what url_params is being set to and compare it with your route matchers.

There might be an easier way to overwrite this, but this seemed pretty straightforward and consistent with how will_paginate expects you to customize its output. I found that Rob Anderton has a great article on customizing will_paginate here, so maybe they can offer more insight.



回答2:

You might also be interested in using Kaminari as an alternative to will_paginate for Rails 3. I discovered it via Railscast and was able to quickly and efficiently integrate it into my app. I also found my app's size decreased and performance increased noticeably after the switch.