【问题标题】:Rails i18n: changing de.errors.format:"%{attribute} %{message}" has no effectRails i18n:更改 de.errors.format:"%{attribute} %{message}" 无效
【发布时间】:2012-05-17 22:08:24
【问题描述】:

我们为我们的应用程序使用了一些自行编写的验证。这些不使用已翻译的内容之一,例如“空”或“无效”。它们采用默认方式“%{attribute} %{message}”

但是,我们的客户要求将它们格式化为“%{attribute}: %{message}.”,只是添加了一些标点符号。

这些是客户 i18n 中的错误消息:

errors:  
  models: 
    foo:
      attributes:
        bar:
          steak_missing: sie haben Ihr Schnitzel vergessen
          beer_missing: sie haben Ihr Bier vergessen

导致丑陋:

Bar sie haben Ihr Schnitzel vergessen 

由于这些可以链接,我们需要这样:

Bar: sie haben Ihr Schnitzel vergessen, sie haben Ihr Bier vergessen.

在基础 i18n 中对此进行了更改:

  errors: &errors
    format: ! "%{attribute}: %{message}." 

完全没有效果。也没有完全删除或其他任何东西。我们正在使用 formtastic 及其 semantic_errors ,它是否为(默认)错误消息提供了自己的 i18n?

【问题讨论】:

  • 您使用的是哪个 Rails i18n 后端?另外,您是否打开了页面、动作或片段缓存?

标签: ruby-on-rails-3 validation internationalization format formtastic


【解决方案1】:

如果我正确理解您的问题 - 您在表单中使用了类似的内容:

<%= f.semantic_errors :bar %>

要更改semantic_errors 的行为,您可以对该方法进行猴子补丁。为此,只需添加文件{RAILS_ROOT}/config/initializers/semantic_errors_patch.rb 的内容:

Formtastic::Helpers::ErrorsHelper.class_eval do
  def semantic_errors(*args)
    html_options = args.extract_options!
    args = args - [:base]

    full_errors = args.inject([]) do |array, method|
      attribute = localized_string(method, method.to_sym, :label) || humanized_attribute_name(method)
      errors = Array(@object.errors[method.to_sym]).to_sentence
      errors.present? ? array << [attribute, errors].join(": ") : array ||= []
    end
    full_errors << @object.errors[:base]
    full_errors.flatten!
    full_errors.compact!

    return nil if full_errors.blank?

    html_options[:class] ||= "errors"
    template.content_tag(:ul, html_options) do
      Formtastic::Util.html_safe(full_errors.map { |error| template.content_tag(:li, Formtastic::Util.html_safe(error)) }.join)
    end
  end
end

此补丁适用于formtastic 2.2.1rails 3.2.13

此补丁将为两个错误生成下一个字符串:

酒吧:sie haben Ihr Schnitzel vergessen 和 sie haben Ihr Bier vergessen。

如果有更多错误,它会产生类似:

金额:不是数字,不能为空,且太短(最少2个字符)

你可以在这一行改变这种行为:

errors = Array(@object.errors[method.to_sym]).to_sentence

@object.errors[method.to_sym] - 是产生最终errors 字符串的错误集合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 2023-02-04
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多