从活动记录错误视图页面更改validation错误以清除闪存消息

我在如何validation数组字段的成员中找到以下代码? 。

# Validates the values of an Enumerable with other validators. # Generates error messages that include the index and value of # invalid elements. # # Example: # # validates :values, enum: { presence: true, inclusion: { in: %w{ big small } } } # class EnumValidator  before_errors prefix = "element #{@count} (#{value}) " (before_errors...error_count).each do |pos| error_messages[pos] = prefix + error_messages[pos] end end end def run_validator(validator, value) validator.validate_each(@record, @attribute, value) rescue NotImplementedError validator.validate(@record) end def error_messages @record.errors.messages[@attribute] end def error_count error_messages ? error_messages.length : 0 end end def create_validator(key, args) opts = {attributes: attributes} opts.merge!(args) if args.kind_of?(Hash) validator_class(key).new(opts).tap do |validator| validator.check_validity! end end def validator_class(key) validator_class_name = "#{key.to_s.camelize}Validator" validator_class_name.constantize rescue NameError "ActiveModel::Validations::#{validator_class_name}".constantize end end 

这是我发现validation一个期望数组的rails表单输入的唯一方法。 问题是无效条目的错误消息不在干净的闪存消息中,而是典型的rails错误页面:

无效条目的错误消息

例如,我的表单有一个多选输入字段,用户可以在其中输入列表中的多个标签。 如果用户输入的标签不是列表中的标签,我希望进行validation,并告知用户必须从列表中选择一个项目。 如何将错误消息更改为干净的flash消息?

似乎validation器引发了错误,而不是简单地将错误消息添加到错误堆栈。 我建议update_attributes block in a update / rescue / end`块中包装update_attributes block in a块。

要更改消息,您可以采用两种方式:

  1. 您可以自定义EnumValidator以使用您的语言环境文件中的键,以便每个条目都可以说“元素%{count}不在列表中”。 您应该能够为消息中的“不在列表中”部分自定义activerecord.errors.messages.inclusion 。 对于“元素0(轨道)”部分,您可以对当前实现的短语进行硬编码(不推荐),也可以通过添加一个键,例如enum_element再次使用语言环境文件,然后在您的EnumValidator中,调用I18n.translate(:'activerecord.errors.messages.enum_element', count: @count, value: value)

  2. validation后,检查errors.keys以查找可枚举列上的问题。 如果发现错误,请删除这些密钥并为该密钥添加自己的消息。

至于你的表单,听起来你正在使用动态表单构建器。 如果它是SimpleForm,您可以尝试使用as: :select选项指定输入的确切类型。