10

Kaminari's URL generation omits the page param if it is generating the link back to the first page. However, the application is designed to select a random page if the page parameter is omitted. Kaminari's default behaviour, then, precludes paginating back to the first page in a reliable way.

I've resolved this issue, and will post my solution below a bit later, but I wanted to post this question for posterity, and I'm also pretty new to Rails, thus I'm not sure my solution is the best or most elegant, and I'm interested in improvements and refinements, if just for my own selfish edification!

4

4 回答 4

14

Kaminari 中实现我们想要更改的行为的代码行在lib/kaminari/helpers/tags.rb方法中Kaminari::Helpers::Tag::page_url_for

  def page_url_for(page)
    @template.url_for @template.params.merge(@param_name => (page <= 1 ? nil : page))
  end

为了覆盖这种行为,我创建了一个文件lib/kaminari/helpers/tag.rb,其中包含以下内容:

module Kaminari
  module Helpers
    class Tag
      def page_url_for(page)
        @template.url_for @template.params.merge(@param_name => (page < 1 ? nil : page))
      end
    end
  end
end

然后我通过将以下行添加到文件中来修补config/initializers/extensions.rb

require "lib/kaminari/helpers/tag.rb"

对于 Ruby/Rails 术语的任何尴尬,我深表歉意,我对 Ruby 还是很陌生。欢迎评论和批评。

于 2011-03-30T17:01:12.553 回答
8

更新

新版本的 kaminari 源代码将要求将其作为更新的行:

@template.url_for @params.merge(@param_name => (page))

否则,您将丢失传递给分页调用的其他参数。

为了清楚起见,这里是新代码的完整输出:

module Kaminari
  module Helpers
    class Tag
      def page_url_for(page)
        @template.url_for @params.merge(@param_name => (page))
      end
    end
  end
end

您仍将按照 Daniel 的建议将其放在初始化程序文件中。

于 2012-07-27T21:57:26.900 回答
6

截至今天(2016 年 7 月),Kaminari主分支包含一个默认配置选项params_on_first_pagefalse

将此配置选项设置为true将包括所有页面的页面参数,包括第 1 页。

请注意,主分支不是稳定版本,因此请谨慎使用!

于 2016-07-30T16:57:08.720 回答
2

这是我写这篇文章的 2018 年的答案:

就像在kaminari github 主页中所述

运行这个来为 kaminari 创建一个配置文件:

rails g kaminari:config

这将在您的 config/initializers 文件夹中创建一个文件 kaminari_config.rb

取消注释行 :config.params_on_first_page = false并将 false 替换为 true :

config.params_on_first_page = true

如有必要,重新启动服务器。而已 :)

于 2018-02-01T12:55:35.463 回答