Merge pull request #37447 from jonathankwok/i18n-error-lookup-for-indexed-attribute

Support ActiveModel::Error translation lookup on indexed attributes.
This commit is contained in:
Rafael França 2019-10-15 17:54:35 -04:00 committed by GitHub
commit c2a002b98d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 0 deletions

View File

@ -69,6 +69,8 @@ module ActiveModel
if base.class.respond_to?(:i18n_scope)
i18n_scope = base.class.i18n_scope.to_s
attribute = attribute.to_s.remove(/\[\d\]/)
defaults = base.class.lookup_ancestors.flat_map do |klass|
[ :"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
:"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ]

View File

@ -26,6 +26,16 @@ class ErrorTest < ActiveModel::TestCase
end
end
class Manager < Person
def read_attribute_for_validation(attr)
try(attr)
end
def self.i18n_scope
:activemodel
end
end
def test_initialize
base = Person.new
error = ActiveModel::Error.new(base, :name, :too_long, foo: :bar)
@ -144,6 +154,15 @@ class ErrorTest < ActiveModel::TestCase
}
end
test "message with type as a symbol and indexed attribute can lookup without index in attribute key" do
I18n.backend.store_translations(:en, activemodel: { errors: { models: { 'error_test/manager': {
attributes: { reports: { name: { presence: "must be present" } } } } } } })
error = ActiveModel::Error.new(Manager.new, :'reports[0].name', :presence)
assert_equal "must be present", error.message
end
test "message uses current locale" do
I18n.backend.store_translations(:en, errors: { messages: { inadequate: "Inadequate %{attribute} found!" } })
error = ActiveModel::Error.new(Person.new, :name, :inadequate)