使用will_paginate的RESTful分页路由

时间:2010-01-18 18:58:30

标签: ruby-on-rails

我有这样的嵌套路线:

map.resources :foo do |foo|
  foo.resources :bar do |bar|
    bar.resources :baz
  end
end

我在每个资源的索引操作中都有分页列表,我需要缓存每个页面,为此我需要路由是RESTful,我该如何为它实现REFTful路由?

例如我希望路线是这样的:

http://www.example.com/foo/:id/pages/:page_number
http://www.example.com/foo/:id/bar/:id/pages/:page_number

2 个答案:

答案 0 :(得分:5)

在app / helpers /

中创建custom_link_renderer.rb
class CustomLinkRenderer < WillPaginate::LinkRenderer
  def page_link(page, text, attributes = {})
    @template.link_to text, "#{@template.url_for(@url_params)}/pages/#{page}", attributes
  end
end

将此行添加到config/environment.rb

WillPaginate::ViewHelpers.pagination_options[:renderer] = 'CustomLinkRenderer'

答案 1 :(得分:2)

我遇到了同样的问题。我这样编写了自己的LinkRenderer来充分利用嵌套路由。

class PaginationListLinkRenderer < WillPaginate::ViewHelpers::LinkRenderer


protected

  def page_number(page)
    unless page == current_page
      if !@options[:params][:url].to_s.empty?
        tag(:li, link(page, @options[:params][:url] + "?page=" + page.to_s))
      else
        tag(:li, link(page,  page, :rel => rel_value(page)))
      end
    else
      tag(:li, page, :class => "current")
    end
  end

  def previous_or_next_page(page, text, classname)
    if page
      if !@options[:params][:url].to_s.empty?
        tag(:li, link(text, @options[:params][:url] + "?page=" + page.to_s, :class => classname))
      else
        tag(:li, link(text,  page, :rel => rel_value(page), :class => classname))
      end
      #tag(:li, link(text, page), :class => classname)
    else
      tag(:li, text, :class => classname + ' disabled')
    end
  end

  def html_container(html)
    tag(:ul, html, container_attributes)
  end

end

然后你必须用这个参数调用will_paginate:

<%= will_paginate :params => { :url => project_task_lists_path(@project) }, :renderer => PaginationListLinkRenderer %>

我希望这会有所帮助:)