0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ruby on Rails】更新日、作成日を好みの表記に変更する

Posted at

目標

デフォルトの表記ではなく、
2020年09月◯◯日や2020/09/◯◯
11時05分や11:05と変更する

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

流れ

1 gem 'rails-i18n'を導入
2 config/application.rbを編集
3 viewを変更

gem 'rails-i18n'を導入

Gemfile
gem 'rails-i18n'
ターミナル
$ bundle install

config/application.rbを編集

config.load_defaults以下4行を追記。

config/application.rb
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2
    config.paths.add 'lib', eager_load: true
    config.time_zone = 'Tokyo'
    config.i18n.default_locale = :ja
    config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
  end

viewを変更

下記のように記載すればOKです。

app/views/posts/show.html.erb
<%= @post.updated_at.strftime("%Y年%m月%d日").to_s %>
<%= @post.updated_at.strftime("%Y/%m/%d").to_s %>
<%= @post.created_at.strftime("%H時%M分").to_s %>
<%= @post.created_at.strftime("%H:%M").to_s %>

補足

gem 'rails-i18n'を使えばエラーの表記も日本語にできます。
詳しくはこちら

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?