【问题标题】:Remove prepended attribute name from full error messages for errors[:base]从errors[:base]的完整错误消息中删除前置属性名称
【发布时间】:2014-06-09 21:20:57
【问题描述】:

我们正在创建一个使用 dynamic_form gem 来显示错误消息的 Rails 表单。对于表单与之交互的模型之一,我们创建了一个自定义验证器:

class Contact < ActiveRecord::Base
  belongs_to :agency

  validate :new_signups_have_contact_information

  def new_signups_have_contact_information
    if agency && agency.is_new_signup?
      unless (email && email != '') || (phone && phone != '')
        errors[:base] << "Please include a phone number or email."
      end
    end
  end
end

到目前为止,一切都很好。但是,当我们显示这些错误时,我们的视图:

<%= form_for @contact do |contact_form| %>
  <%= contact_form.error_messages %>
  <%# snip %>
<% end %> 

我们在验证失败时生成的错误中收到此消息:

联系人基地请提供电话号码或电子邮件。

我们如何从生成的错误字符串中删除前置的“Contacts base”?


我们进行了一些研究:我们知道这是因为默认情况下,Rails 的错误消息系统automatically prepends attribute names to their error strings。另外,在大多数情况下,我们可以将modify the English localization file 转为remove the prepended strings

然而,Rails 官方指南并未列出如何更改提供给 errors[:base] 数组或使用自定义验证生成的错误消息的本地化。它列出了如何覆盖为all of the built-in validations 生成的字符串,但没有其他错误。

因此,我们愿意使用一种方法:我们如何配置 config/locales/en.yml 以删除前置的“Contacts base”字符串?


我们研究过的另一种我们不想使用的方法是打开ActiveRecord::Errors 类并编写我们自己的errors#full_messages 函数实现。 (This blog post 描述了该技术。)这种方法改变了整个项目的 ActiveRecord::Errors 类的行为,我们宁愿使用一种对局部影响更大的方法。 如果我们不能使用 lcoalization 文件来实现我们想要的,有没有比打开 ActiveRecord:Errors 类更直接的方法?


编辑

contact.errors 哈希是:

$ contact.errors.to_yaml
--- !ruby/object:ActiveModel::Errors
base: !ruby/ActiveRecord:Contact
  attributes:
    id:
    # snip
messages: !omap
- :base:
  - Please include a phone number or emai.

【问题讨论】:

  • 您已通过this 确定了正确的解决方案。您是否遇到无法解决的问题?
  • 是的。我不确定如何配置本地化文件来更改用于我们自定义验证器的字符串。我猜它类似于activerecord.errors.models.contact.attributes.base.&lt;what goes here?&gt;activerecord.errors.models.contact.attributes.&lt;our custom validator&gt;。我缺少的字符串部分是什么?
  • 它可能正在调用 activerecord.attributes.contacts.base(不正确)。您的错误哈希的整体情况如何?
  • @BookOfGreg 我将错误哈希编辑到我的问题中。
  • 我只是想知道它是否将 base 作为属性读取。设置 activerecord.attributes.contacts.base 有什么作用吗?

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

看起来你的验证器正在使 :base 显示为一个属性,用这个语言环境覆盖它。

# config/locales/en.yml
en:
  activerecord:
    attributes:
      contacts:
        base: "" 

【讨论】:

    【解决方案2】:

    记住错误信息的各种属性也可以配置

    # config/locals/en.yml
    en:
      activerecord:
        attributes:
          contacts:
            base: ""
       errors:
         messages:
           blank: "missing"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      相关资源
      最近更新 更多