0
0

More than 1 year has passed since last update.

【Rails】モデル名.human_attribute_name(:カラム名) 使い方

Posted at

はじめに

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.ymlattributes/id/'ID'を参照する
Todo.human_attribute_name(:name)
 config/locales/ja.ymlattributes/name/'名称'を参照する
Todo.human_attribute_name(:description)
 config/locales/ja.ymlattributes/:description/'詳しい説明'を参照する
0
0
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
0
0