How to Implement ajax pagination with will_paginate gem

前端 未结 6 943
遥遥无期
遥遥无期 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:46

    I want to expand on Pierre's answer.

    If you are using materialize sass with will_paginate_materialize then you will have an initializer to style the pagination links.

    gem 'will_paginate', '~> 3.1.0'

    gem 'will_paginate-materialize', git: 'https://github.com/mldoscar/will_paginate-materialize', branch: 'master'

    So, in order to get the remote true to work on the links rendered by the will_paginate_materialize initializer I did this:

    will_paginate_helper.rb

    module WillPaginateHelper
      class WillPaginateJSLinkRenderer < WillPaginate::ActionView::LinkRenderer
      end
      def js_will_paginate(collection, options = {})
        will_paginate(collection, options.merge(:renderer =>WillPaginateHelper::WillPaginateJSLinkRenderer))
      end
    end
    

    I changed the will paginate materialize initializer to look like this:

    will_paginate_materialize.rb

    MaterializePagination::MaterializeRenderer.module_eval do
      def page_number(page)
        classes = ['waves-effect', ('active' if page == current_page)].join(' ')
        tag :li, link(page, page, :rel => rel_value(page)), class: classes
      end
    
      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
    
    WillPaginate::ViewHelpers::LinkRenderer.class_eval do
      def symbolized_update(target, other, blacklist = nil)
        other.each_pair do |key, value|
          key = key.to_sym
          existing = target[key]
          next if blacklist && blacklist.include?(key)
    
          if value.respond_to?(:each_pair) and (existing.is_a?(Hash) or existing.nil?)
            symbolized_update(existing || (target[key] = {}), value)
          else
            if value.instance_variable_defined?(:@parameters)
              value = value.instance_variable_get(:@parameters)
            end
            target[key] = value
          end
        end
      end
    end
    

    In my view I left the renderer in the will paginate link the same:

    = will_paginate results, renderer: MaterializePagination::Rails

提交回复
热议问题