LoginSignup
4
2

More than 3 years have passed since last update.

【Rails】created_atを使って「〇〇分前」と表示したい!

Last updated at Posted at 2021-01-12

概要

本記事ではRailsのcreated_atで作成日時を表示する際に、従来の時間表記ではなく「〇〇分前」のように表示する方法を記載しています。
完成イメージは以下の通りです。
スクリーンショット 2021-01-12 22.01.28.png

開発環境

  • Ruby 2.6.5p114
  • Rails 6.0.3.4

手順

① 日本語設定をする

まずは、日本語設定をします。
configのapplication.rbファイルに以下を記述してください

config/application.rb
config.i18n.default_locale = :ja

② 日本語のyamlファイルを作成する

次に、どのような日本語表記にするかyamlファイルに設定を書いていきます。
日本語に関するja.ymlはRailsにデフォルトで入っていないため、以下を参考に作成してください。
ja.ymlファイルはconfig/locales配下に作成します。

config/locales/ja.yml
ja:
  datetime:
    distance_in_words:
      about_x_hours:
        one: 1時間
        other: %{count}時間
      about_x_months:
        one: 1ヶ月
        other: %{count}ヶ月
      about_x_years:
        one: 1
        other: %{count}
      almost_x_years:
        one: 1年弱
        other: "%{count}年弱"
      half_a_minute: 30秒前後
      less_than_x_seconds:
        one: 1秒以内
        other: "%{count}秒未満"
      less_than_x_minutes:
        one: 1分以内
        other: "%{count}分未満"
      over_x_years:
        one: 1年以上
        other: "%{count}年以上"
      x_seconds:
        one: 1
        other: "%{count}秒"
      x_minutes:
        one: 1
        other: "%{count}分"
      x_days:
        one: 1
        other: "%{count}日"
      x_months:
        one: 1ヶ月
        other: "%{count}ヶ月"
      x_years:
        one: 1
        other: "%{count}年"

③ ビューで表示する

最後にビューで表示します。
表示する際は、Railsが用意してくれているtime_ago_in_wordsメソッドを使用します。
引数には作成日時を渡します。

index.html.erb
<p>#{time_ago_in_words(post.created_at)}前にアウトプット</p>

※postの部分は適宜書きかえてください



以上で実装が完了しました!
表示方法を自分好みに修正したい時はja.ymlにて修正してください。

4
2
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
4
2