3
2

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.

translation missing: ja~ 系のエラー。日本語、英語どちらも対応させる。

Last updated at Posted at 2021-04-14

##前提知識
https://railsguides.jp/i18n.html

なぜこのエラーが出たのか

###ja.yml内に、該当する値が存在しないから

以前Fakerを日本語化したため、Railsアプリのデフォルトが日本語になっていた。

application.rb
    config.i18n.available_locales = %i[ja en]
    config.i18n.default_locale = :ja


Rspecを行った。

spec/models./post_spec.rb
 it 'is invalid without a title' do
     post = Post.new()
     post.valid?
     expect(post.errors.messages[:title]).to include('can`t be blank')
  end


エラー発生

 Failure/Error: expect(post.errors.messages[:title]).to 
include('Can not be blank')
expected #<ActiveModel::DeprecationHandlingMessageArray(["translation missing: ja.activerecord.errors.models.post.attributes.title.blank"])> to include "Can not be blank"

大事なところ

translation missing: 
ja.activerecord.errors.models.post.attributes.title.blank"


####ja.ymlのja.activerecord.errors.models.post.attributes.title.blankに対する値がないというエラー。

##解決方法
ja.ymlにエラーに書かれている内容通りに設定する
"ja.activerecord.errors.models.post.attributes.title.blank"

ja.yml
ja:
  activerecord:
    errors:
      models:
        post:
          attributes:
            title:
              blank: "タイトルが空白です"

rails cで確認してみる

pry(main)> I18n.t("activerecord.errors.models.post.attributes.title.blank")
=> "タイトルが空白です。"

rspecを直す

spec/models./post_spec.rb
 it 'is invalid without a title' do
     post = Post.new()
     post.valid?
     - expect(post.errors.messages[:title]).to include('can`t be blank')
     + expect(post.errors.messages[:title]).to include(I18n.t("activerecord.errors.models.post.attributes.title.blank"))

  end

Rspec無事通りました。

参考:
https://railsguides.jp/i18n.html#%E8%A8%B3%E6%96%87%E3%81%AE%E5%8F%82%E7%85%A7
https://qiita.com/punkshiraishi/items/bdb2d48425782e25eadc
https://qiita.com/shimadama/items/7e5c3d75c9a9f51abdd5
https://pikawaka.com/rails/i18n

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?