はじめに
Railsの参考書を読んでいた時に、human_attribute_nameについて、
理解していなかった為、簡単にまとめます。
モデル名.human_attribute_name(:カラム名)とは?
ActiveRecord::Base のクラスメソッドで内部的にI18nモジュールを利用してくれるというものです。
まず、config/locales/ja.ymlに参照元を書いていきます。
config/locales/ja.ymlに定義
config/locales/ja.yml
ja:
activerecord:
errors:
messages:
record_invalid: 'バリデーションに失敗しました: %{errors}'
restrict_dependent_destroy:
has_one: "%{record}が存在しているので削除できません"
has_many: "%{record}が存在しているので削除できません"
models:
task: 'タスク'
attributes:
task:
id: 'ID'
name: '名称'
description: '詳しい説明'
created_at: '登録日時'
updated_at: '更新日時'
使用法
show.html.haml
Todo.human_attribute_name(:id)
→config/locales/ja.ymlのattributes/id/の'ID'を参照する
Todo.human_attribute_name(:name)
→config/locales/ja.ymlのattributes/name/の'名称'を参照する
Todo.human_attribute_name(:description)
→config/locales/ja.ymlのattributes/:description/の'詳しい説明'を参照する