how to use rails i18n fallback features

2019-01-12 01:49发布

I have this i18n problem

activerecord:
  notices:
    messages:
      success: 
        create: "Something was created"
    models:
      user:
        success:
            create: "Thanks for registration"

I18n.t("activerecord.notices.models.user.success.create")
# => "Thanks for registration"


I18n.t("activerecord.notices.models.book.success.create") 
# => "translation missing: de, activerecord, notices, models, book, success, create"

I don't know why the book model doesn't get the fallback massage. I have set config.i18n.fallbacks = true. I'm using Rails 3

5条回答
趁早两清
2楼-- · 2019-01-12 02:15

In rails 3+, this is set in the config/environments files :

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.fallbacks = true
查看更多
等我变得足够好
3楼-- · 2019-01-12 02:22

When a :default option is given, its value will be returned if the translation is missing:

I18n.t :missing, :default => 'Not here'
# => 'Not here'

More info here

查看更多
够拽才男人
4楼-- · 2019-01-12 02:24

I believe the best way to handle a missing string, is to display a default locale, rather than an error message.

Add this line in application.rb to fallback to the english locale.

config.i18n.fallbacks = [:en]

In case you want to specify locale-specific fallbacks, you can use the following:

config.i18n.fallbacks = {:de => [:de,:en], :en => [:en,:de]}

Also, note that you can enable and disable fallbacks based on your environment. So while on development it might make sense to have an error displayed, you can instead enable fallbacks in your environments/production.rb with the following:

config.i18n.fallbacks = true
查看更多
淡お忘
5楼-- · 2019-01-12 02:25

Have you enabled fallbacks for your backend? Assuming it's Simple(based on yml in example):

put this in an initializer:

require "i18n/backend/fallbacks" 
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)

https://github.com/svenfuchs/i18n/wiki/Fallbacks

查看更多
6楼-- · 2019-01-12 02:27

I set in config/application.rb usually

    config.i18n.fallbacks =[:de, :fr, :en]

So you can decelerate the order of the fallback.

But keep attention in some environments/*.rb the configuration is overwritten.

查看更多
登录 后发表回答