How to Implement ajax pagination with will_paginate gem

前端 未结 6 936
遥遥无期
遥遥无期 2020-12-02 10:19

I am using will_paginate gem in my ROR project to show the records in pages.

I want the next page to be loaded without reloading the whole

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 10:37

    Create a new helper (ex. app/helpers/will_paginate_helper.rb) with the following content:

    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
    

    Then in your view use this tag for ajax pagination:

    <%= js_will_paginate @recipes %>
    

    Remember that the pagination links will include existing params of the url, you can exclude these as shown below. This is standard will paginate functionality:

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

    Hope that solves your problem.

    Update 1: Added a explanation of how this works to the original question where I posted this solution.

    Update 2: I've made it Rails 4 compatible with remote: true links and renamed the helper method to js_will_paginate.

提交回复
热议问题