ruby on rails will_paginate更改默认链接

时间:2017-01-18 10:55:27

标签: ruby-on-rails will-paginate

routes.rb我设置列表#index为根:

root to: "lists#index"

我希望will_paginate创建指向href而不是/?page=#的网页/lists?page=#。要创建分页链接,我在"列表中有以下行#index"文件:

<%= will_paginate @lists %>

3 个答案:

答案 0 :(得分:3)

解决方案确实是自定义渲染器。谢谢Ayush!

以下帮助我解决了这个问题:how-to-customize-the-will-paginate-links-with-images

我创建了一个文件:app/helpers/will_paginate_helper.rb,其中包含以下内容:

module WillPaginateHelper
  class RootedLinkRenderer < WillPaginate::ActionView::LinkRenderer
    protected
    def link(text, target, attributes = {})
      if target.is_a? Fixnum
        attributes[:rel] = ""
        target = "/?page=#{target}"
      end
      attributes[:href] = target
      tag(:a, text, attributes)
    end
  end
end

最后,我更新了索引文件并替换了:

<%= will_paginate @lists %>

使用:

<%= will_paginate @lists, renderer: WillPaginateHelper::RootedLinkRenderer %>

因此,href为http://localhost:3000/?page=2而非http://localhost:3000/lists?page=2

答案 1 :(得分:1)

我从您的问题中了解到您尝试创建自定义渲染器,虽然我从未使用过它,但是为此您需要覆盖渲染器的链接方法。 这里是原始代码的链接可能会有一些帮助 - https://github.com/voormedia/paginary/blob/master/lib/paginary/helpers/pagination_helper.rb

答案 2 :(得分:1)

在这种特殊情况下,链接会受routes.rb文件中路由指令的顺序影响。

如果您放置

    root to: "lists#index"

位于routes.rb的顶部,然后will_paginate将生成指向/?page=#的链接,而无需自定义渲染器。

这可以在课程的模块常见问题解答中找到。