mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Support ActiveModel::Error translation lookup on indexed attributes.
Instances of ActiveModel::Error where `attribute` is a nested attribute can use translation keys that don't include the index in their lookup key.
This commit is contained in:
parent
94584c2510
commit
5c9b008f36
2 changed files with 26 additions and 2 deletions
|
@ -69,9 +69,14 @@ module ActiveModel
|
|||
|
||||
if base.class.respond_to?(:i18n_scope)
|
||||
i18n_scope = base.class.i18n_scope.to_s
|
||||
unindexed_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}" ]
|
||||
[
|
||||
:"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
|
||||
:"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{unindexed_attribute}.#{type}",
|
||||
:"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}"
|
||||
]
|
||||
end
|
||||
defaults << :"#{i18n_scope}.errors.messages.#{type}"
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in a new issue