小编典典

如何使用will_paginate gem实现ajax分页

ajax

will_paginateROR项目中使用gem 来显示页面中的记录。

我希望加载下一页而不使用重新加载整个页面ajax

我在网上找到了一些示例,但它们对我不起作用。

这该怎么做?


阅读 449

收藏
2020-07-26

共1个答案

小编典典

使用以下内容创建一个新的助手(例如app / helpers / will_paginate_helper.rb):

module WillPaginateHelper
  class WillPaginateJSLinkRenderer < WillPaginate::ActionView::LinkRenderer
    def prepare(collection, options, template)
      options[:params] ||= {}
      options[:params]['_'] = nil
      super(collection, options, template)
    end

    protected
    def link(text, target, attributes = {})
      if target.is_a? Fixnum
        attributes[:rel] = rel_value(target)
        target = url(target)
      end

      @template.link_to(target, attributes.merge(remote: true)) do
        text.to_s.html_safe
      end
    end
  end

  def js_will_paginate(collection, options = {})
    will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateJSLinkRenderer))
  end
end

然后在您的视图中使用此标记进行ajax分页:

<%= js_will_paginate @recipes %>

请记住,分页链接将包含URL的现有参数,您可以如下所示排除这些参数。这是标准的分页功能:

<%= js_will_paginate @recipes, :params => { :my_excluded_param => nil } %>

希望能解决您的问题。

更新1 :在我发布此解决方案的原始问题中添加了对此工作原理的解释。

更新2 :我已经使Rails 4与remote:true链接兼容,并将helper方法重命名为 js_will_paginate

2020-07-26