13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

kaminariのpage_entries_info はデフォルトだと英語環境でしか使えないので対応

Posted at

概要

Rails上で「全体1000件中100件ずつ、合計10ページに分けて表示する」みたいなページング処理するときの定番gemのkaminariですが、英語環境以外だと問題が発生します。

page_entries_info が使えない

「今3ページ目で、201件目から300件目まで表示している」みたいな表示がしたい時に<%= page_entries_info @posts %>のように記述するとできるようですが、言語環境がen(英語)以外だと動作しません!!

config/application.rb 言語設定の抜粋
    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de
    config.i18n.default_locale = :ja

どうしよう・・・。

環境(参考までに)

  • rails (4.2.6)
  • kaminari (0.16.3)

解法1:強引にページング処理を実装する(非推奨)

車輪の再発明的な行為です。

コントローラの改修例
  def index
    @per_page = 50
    @offices = Office.page(params[:page]).per(@per_page)
    @total_records = Office.count
    # 最初のページの場合 params[:page]} が存在しないので 1ページ目とする。

    params[:page].blank? ? @current_page = 1 :  @current_page  = params[:page].to_i
    if @current_page == 0 then @current_page += 1 end

    @current_start = @per_page * (@current_page - 1 ) + 1
    @current_end   = @current_start + @per_page - 1
  end
ビューに表示項目を追加
<p>
合計 <%= @total_records %> 現在 <%= @current_page %> 頁目で
<%= @current_start %> 件目から <%= @current_end %> 件目まで表示中
</p>

すごく・・・強引です。

解法2 ロケールが日本語の場合に読み込む設定を用意する

Ruby on Railsにおいては、特に何も設定しないとロケールが英語(en)になります。
日本語以外の言語を使おうとすると、対応する設定を用意します。

Railsでkaminariを使ってページネーションを実現する
の記述によると、「最初のページを表示する」などに相当する文言はymlファイルで管理しているようだ。

githubによると・・・確かにそうだ。英語しかない。
ソースを確認

ロケールファイルに追記

実際のところは、ロケールファイルに日本語の設定がなかったことが原因。こんな感じのロケールファイルを用意する。

viewの記述
  views:
    pagination:
      first:    "最初のページ"
      last:     "最後のページ"
      previous: "&lsaquo;"
      next:     "&rsaquo;"
      truncate: "(中略)"
helperの記述
    page_entries_info:
      one_page:
        display_entries:
          zero: "%{entry_name} が存在しません"
          one:  "%{entry_name}  <b>all %{count}</b> 1ページ目のみ"
          other: "全体で <b> %{count}</b> 件 %{entry_name}"
      more_pages:
        display_entries: " %{entry_name} <b>%{first}&nbsp;-&nbsp;%{last}</b> までを表示中 全体で <b>%{total}</b> 件"

上記のような設定を configure/ja.ymlなどに追記するのですが、
微妙にズレてエラーになることが多いので注意。

13
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?