How can I stop rails globalize from falling back to the fallback locale on just one field?

320 Views Asked by At

We use the globalize gem and have included Rails.application.config.i18n.fallbacks = [:en] in config/initializers/i18n.rb so that the user sees the English translation of a field if one does not exist in their own language.

That means we see this behavior, as expected:

class Post < ActiveRecord::Base
  translates :title, :name
end

puts post.translations.inspect
# => [#<Post::Translation id: 1, post_id: 1, locale: "en", title: "Globalize rocks!", name: "Globalize">,
      #<Post::Translation id: 2, post_id: 1, locale: "nl", title: '', name: nil>]

I18n.locale = :en
post.title # => 'Globalize rocks!'
post.name  # => 'Globalize'

I18n.locale = :nl
post.title # => ''
post.name  # => 'Globalize'

In just one place where we are displaying "posts", the client asked us to not show anything if there is no translation for the "name". Is there a built in way to do this? I.e.:

I18n.locale = :nl
post.title # => ''
post.name_if_translated  # => nil
1

There are 1 best solutions below

0
lucas On

I did find one workaround:

post.name_translations[I18n.locale]

But maybe there's a better way?