Skip to content

Commit

Permalink
Fallback on "invalid" with missing translation
Browse files Browse the repository at this point in the history
When `config.i18n.raise_on_missing_translations` is enabled, Rails 7.1
raises on missing translation error when validation messages are not
translated, which is a new behavior causing CSV to fail

For unsupported validations, like `comparison`, and custom validations,
like `timeliness`, CSV attempts to create a message for a key that
is not present.

This commit standardizes the behavior and fallbacks on "invalid" when
a translation is not found, which is supposed to be the desired
behavior for this use case

Close #920
  • Loading branch information
tagliala committed Oct 8, 2023
1 parent 91752fc commit 00e297a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
19 changes: 18 additions & 1 deletion lib/client_side_validations/active_model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,24 @@ def copy_conditional_attributes(attribute_to, attribute_from)
private

def build_client_side_hash(model, attribute, options)
{ message: model.errors.generate_message(attribute, message_type, options) }.merge(options.except(*callbacks_options - %i[allow_blank if unless]))
# Rails mutates `options` object when calling `model.errors.generate_message`
# by removing `message` option, if any.
# By raising on missing translations, CSV has the same behavior across
# all supported Rails versions and `config.i18n.raise_on_missing_translations`
# possible configurations.
options[:raise] = true

message =
begin
model.errors.generate_message(attribute, message_type, options)
rescue I18n::MissingTranslationData
options[:message] = :invalid
model.errors.generate_message(attribute, message_type, options)
end

options.delete(:raise)

{ message: message }.merge(options.except(*callbacks_options - %i[allow_blank if unless]))
end

def message_type
Expand Down
17 changes: 17 additions & 0 deletions test/active_model/cases/test_validations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,23 @@ def test_multiple_validators_of_same_type_on_same_attribute
assert_equal expected_hash, person.client_side_validation_hash
end

def test_missing_translation
person = new_person do |p|
p.validates :first_name, comparison: { other_than: :last_name }
end

expected_hash = {
first_name: {
comparison: [{
message: 'is invalid',
other_than: :last_name
}]
}
}

assert_equal expected_hash, person.client_side_validation_hash
end

def test_ignored_procs_validators
person = new_person do |p|
p.validates :first_name, format: proc { |o| o.matcher }
Expand Down

0 comments on commit 00e297a

Please sign in to comment.