LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】日本語に変換したcreated_atを配列にする

Posted at

初学者のインプット内容の整理のための記事です。
'rails-i18n'gemを使ってモデルのcreated_atを日本語で配列としてインスタンス変数に保存する方法です。

参考にしたページ:
https://opiyotan.hatenablog.com/entry/rails_gem_i18n
https://teratail.com/questions/53958

準備

Gemfile.
#追加
gem 'rails-i18n'
bundle install

次にconfig/locales/ja.ymlを作成する。
rails-i18n/ja.yml at master · svenfuchs/rails-i18n · GitHub の内容をそのファイルにコピペする。

配列取得

#通常の実行結果
@items = @user.items.map{|item| item.created_at}
puts @items
=> 2021-11-07 21:09:50 +0900
   2021-11-07 21:07:41 +0900
   2021-11-03 21:43:22 +0900
   2021-11-03 21:43:19 +0900
#I18nを利用した実行結果
@items = @user.items.map{|item| I18n.l(item.created_at)}
puts @items
=> 2021年11月07日(日) 21時09分50秒 +0900
   2021年11月07日(日) 21時07分41秒 +0900
   2021年11月03日(水) 21時43分22秒 +0900
   2021年11月03日(水) 21時43分19秒 +0900
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