Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fix human attribute_name to handle deeply nested attributes

When a model nests another model that also nests yet another model
using accepts_nested_attributes_for method, its Errors object can
have an attribute name with "contacts.addresses.street" style.

In this case, the dots within the namespace should be substituted
with slashes so that we can provide the translation under the
"activemodel.attributes.person/contacts/addresses.street" key.

This commit is related to #3859.
  • Loading branch information...
commit b0e2fc843b555f94a4472ed50b337dc5048c8b8c 1 parent 7994496
Tsutomu Kuroda authored
4 activemodel/lib/active_model/translation.rb
@@ -42,9 +42,9 @@ def lookup_ancestors
42 42 # Specify +options+ with additional translating options.
43 43 def human_attribute_name(attribute, options = {})
44 44 options = { :count => 1 }.merge!(options)
45   - parts = attribute.to_s.split(".", 2)
  45 + parts = attribute.to_s.split(".")
46 46 attribute = parts.pop
47   - namespace = parts.pop
  47 + namespace = parts.join("/") unless parts.empty?
48 48 attributes_scope = "#{self.i18n_scope}.attributes"
49 49
50 50 if namespace
5 activemodel/test/cases/translation_test.rb
@@ -56,6 +56,11 @@ def test_translated_model_attributes_with_attribute_matching_namespaced_model_na
56 56 assert_equal 'person gender attribute', Person::Gender.human_attribute_name('attribute')
57 57 end
58 58
  59 + def test_translated_deeply_nested_model_attributes
  60 + I18n.backend.store_translations 'en', :activemodel => {:attributes => {:"person/contacts/addresses" => {:street => 'Deeply Nested Address Street'}}}
  61 + assert_equal 'Deeply Nested Address Street', Person.human_attribute_name('contacts.addresses.street')
  62 + end
  63 +
59 64 def test_translated_nested_model_attributes
60 65 I18n.backend.store_translations 'en', :activemodel => {:attributes => {:"person/addresses" => {:street => 'Person Address Street'}}}
61 66 assert_equal 'Person Address Street', Person.human_attribute_name('addresses.street')

0 comments on commit b0e2fc8

Please sign in to comment.
Something went wrong with that request. Please try again.