辞書ファイルをviewでも使いたい
config/locale/views/tasks/ja.yml
ja:
tasks:
index:
index_title: 'タスク一覧'
created_at: '作成日時'
name: 'タスク名'
content: '内容'
show: '詳細'
edit: '編集'
destroy: '削除'
new: '新規タスク作成'
app/views/tasks/index.html.slim
table.table.table-hover
thead.thead-default
= tag.tr do
th = タスク名
th = 内容
th = t 'views.tasks.index.show'
th = t 'activerecord.errors.messages.record_invalid'
th
tbody
- @tasks.each do |task|
= tag.tr do
td = task.name
td = task.content
td = link_to '詳細', task_path(task.id)
td = link_to '編集', edit_task_path(task.id)
td = link_to '削除', task_path(task.id), method: :delete
となり、th = t 'activerecord.errors.messages.record_invalid'はうまく効いてるものの、th = t 'views.tasks.index.show'は何故かshowと表示されてしまう。
解決策
config/application.rb
module AppName
class Application < Rails::Application
# 省略
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
# このコードを追記して複数のlocaleファイルを読み込めるようにする
end
end
辞書ファイルでしっかり指定されていれば、t '.辞書名'でいける。 link_toの中では t('.辞書名')にすることで解決。
以下、置き換えたコード
app/views/tasks/index.html.slim
h1 = t '.index_title'
table.table.table-hover
thead.thead-default
= tag.tr do
th = t '.name'
th = t '.content'
th = t '.show'
th =
th
tbody
- @tasks.each do |task|
= tag.tr do
td = task.name
td = task.content
td = link_to t('.show'), task_path(task.id)
td = link_to t('.edit'), edit_task_path(task.id)
td = link_to t('.destroy'), task_path(task.id), method: :delete
結果
このように記述することで、辞書ファイルを読み込むことができる!