Ruby on Rails で created_atで作成日時を表示する際に、Twitterのように「〜前」という表示をする方法です。
Views
ビューはこんな感じです。
1 |
<%= time_ago_in_words(post.created_at) %>前に作成 |
Locales
configでdefault_localeを日本語に設定します。
config/application.rb
1 |
config.i18n.default_locale = :ja |
こちらを参考に、ja.ymlに datetime、distance_in_words を設定します。
config/locales/ja.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
ja: datetime: distance_in_words: half_a_minute: "30秒前後" less_than_x_seconds: one: "1秒" other: "%{count}秒" x_seconds: one: "1秒" other: "%{count}秒" less_than_x_minutes: one: "1分" other: "%{count}分" x_minutes: one: "約1分" other: "%{count}分" about_x_hours: one: "約1時間" other: "約%{count}時間" x_days: one: "1日" other: "%{count}日" about_x_months: one: "約1ヶ月" other: "約%{count}ヶ月" x_months: one: "1ヶ月" other: "%{count}ヶ月" almost_x_years: one: "1年弱" other: "%{count}年弱" about_x_years: one: "約1年" other: "約%{count}年" over_x_years: one: "1年以上" other: "%{count}年以上" |
次のようなエラーメッセージが出ている場合は、記述ミスがあるか、インデントが合っていないかもしれません。
1 |
translation missing: ja.datetime.distance_in_words.about_x_hours |
rails_i18nで日本語と英語をパラメータで切り替える方法はこちらの記事をご覧ください。
https://remonote.jp/rails_i18n_locale_ja_en
以上です!ご覧いただき、ありがとうございました!!😊