Skip to content

Commit 71fc672

Browse files
authored
Merge pull request rails#54266 from zzak/re-54250
Handle missing attributes for AM::Translation#human_attribute_name
2 parents 85cbf9c + 0e0194a commit 71fc672

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

activemodel/lib/active_model/translation.rb

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,19 @@ def human_attribute_name(attribute, options = {})
5252
namespace, _, attribute = attribute.rpartition(".")
5353
namespace.tr!(".", "/")
5454

55+
if attribute.present?
56+
key = "#{namespace}.#{attribute}"
57+
separator = "/"
58+
else
59+
key = namespace
60+
separator = "."
61+
end
62+
5563
defaults = lookup_ancestors.map do |klass|
56-
:"#{i18n_scope}.attributes.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}"
64+
:"#{i18n_scope}.attributes.#{klass.model_name.i18n_key}#{separator}#{key}"
5765
end
58-
defaults << :"#{i18n_scope}.attributes.#{namespace}.#{attribute}"
66+
defaults << :"#{i18n_scope}.attributes.#{key}"
67+
defaults << :"attributes.#{key}"
5968
else
6069
defaults = lookup_ancestors.map do |klass|
6170
:"#{i18n_scope}.attributes.#{klass.model_name.i18n_key}.#{attribute}"
@@ -69,7 +78,9 @@ def human_attribute_name(attribute, options = {})
6978
defaults << MISSING_TRANSLATION unless raise_on_missing
7079

7180
translation = I18n.translate(defaults.shift, count: 1, raise: raise_on_missing, **options, default: defaults)
72-
translation = attribute.humanize if translation == MISSING_TRANSLATION
81+
if translation == MISSING_TRANSLATION
82+
translation = attribute.present? ? attribute.humanize : namespace.humanize
83+
end
7384
translation
7485
end
7586
end

activemodel/test/cases/translation_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,16 @@ def test_translated_subclass_model_when_ancestor_translation
104104
assert_equal "person model", Child.model_name.human
105105
end
106106

107+
def test_translated_attributes_when_nil
108+
I18n.backend.store_translations "en", activemodel: { attributes: { "person/addresses": { street: "Person Address Street" } } }
109+
assert_equal("Addresses", Person.human_attribute_name("addresses.#{nil}"))
110+
end
111+
112+
def test_translated_deeply_nested_attributes_when_nil
113+
I18n.backend.store_translations "en", activemodel: { attributes: { "person/contacts/addresses": { street: "Deeply Nested Address Street" } } }
114+
assert_equal("Addresses/contacts", Person.human_attribute_name("addresses.contacts.#{nil}"))
115+
end
116+
107117
def test_translated_subclass_model_when_missing_translation
108118
assert_equal "Child", Child.model_name.human
109119
end

0 commit comments

Comments
 (0)