Rails 3 自定义格式验证错误?

发布于 2024-11-09 03:13:05 字数 1623 浏览 0 评论 0原文

使用这个模型:

validates_presence_of :email, :message => "We need your email address"

作为一个相当人为的例子。错误显示为:

Email We need your email address

我如何自己提供格式?

我查看了 ActiveModel::Errors#full_messages 的源代码,它执行以下操作:

def full_messages
  full_messages = []

  each do |attribute, messages|
    messages = Array.wrap(messages)
    next if messages.empty?

    if attribute == :base
      messages.each {|m| full_messages << m }
    else
      attr_name = attribute.to_s.gsub('.', '_').humanize
      attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
      options = { :default => "%{attribute} %{message}", :attribute => attr_name }

      messages.each do |m|
        full_messages << I18n.t(:"errors.format", options.merge(:message => m))
      end
    end
  end

  full_messages
end

注意到选项中的 :default 格式字符串吗?所以我尝试了:

validates_presence_of :email, :message => "We need your email address", :default => "something"

但错误消息实际上显示为:

Email something

然后我尝试包含插值字符串 %{message},从而覆盖 %{attribute} %{message} Rails 默认使用的版本。这会导致异常:

SubscriptionsController#create 中的 I18n::MissingInterpolationArgument

给定的“%{message}”({:model=>"Subscription", :attribute=>"Email", :value=>""} 中缺少插值参数

然而如果我使用插值字符串 %{attribute} ,它不会出错,它只会两次输出人性化的属性名称。

有人有这方面的经验吗?通常我们需要一些其他字符串(营销人员总是让事情变得更复杂!)。

With this model:

validates_presence_of :email, :message => "We need your email address"

as a rather contrived example. The error comes out as:

Email We need your email address

How can I provide the format myself?

I looked at the source code of ActiveModel::Errors#full_messages and it does this:

def full_messages
  full_messages = []

  each do |attribute, messages|
    messages = Array.wrap(messages)
    next if messages.empty?

    if attribute == :base
      messages.each {|m| full_messages << m }
    else
      attr_name = attribute.to_s.gsub('.', '_').humanize
      attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
      options = { :default => "%{attribute} %{message}", :attribute => attr_name }

      messages.each do |m|
        full_messages << I18n.t(:"errors.format", options.merge(:message => m))
      end
    end
  end

  full_messages
end

Notice the :default format string in the options? So I tried:

validates_presence_of :email, :message => "We need your email address", :default => "something"

But then the error message actually appears as:

Email something

So then I tried including the interpolation string %{message}, thus overriding the %{attribute} %{message} version Rails uses by default. This causes an Exception:

I18n::MissingInterpolationArgument in SubscriptionsController#create

missing interpolation argument in "%{message}" ({:model=>"Subscription", :attribute=>"Email", :value=>""} given

Yet if I use the interpolation string %{attribute}, it doesn't error, it just spits out the humanized attribute name twice.

Anyone got any experience with this? I could always have the attribute name first, but quite often we need some other string (marketing guys always make things more complicated!).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白日梦 2024-11-16 03:13:05

:base 上的错误并不特定于任何属性,因此人性化的属性名称不会附加到消息中。这允许我们添加有关电子邮件的错误消息,但不将它们附加到电子邮件属性,并获得预期的结果:

class User < ActiveRecord::Base
  validate :email_with_custom_message
  ...
  private

  def email_with_custom_message
    errors.add(:base, "We need your email address") if
      email.blank?
  end
end

Errors on :base are not specific to any attribute, so the humanized attribute name is not appended to the message. This allows us to add error messages about email, but not attach them to the email attribute, and get the intended result:

class User < ActiveRecord::Base
  validate :email_with_custom_message
  ...
  private

  def email_with_custom_message
    errors.add(:base, "We need your email address") if
      email.blank?
  end
end
吃素的狼 2024-11-16 03:13:05

为此使用国际化可能是您最好的选择。看看

http://guides.rubyonrails.org/i18n .html#translations-for-active-record-models

特别是这一部分:

5.1.2 错误消息插值

翻译后的型号名称,翻译后
属性名称和值始终是
可用于插值。

因此,例如,而不是
默认错误消息“不能
空白”你可以使用该属性
姓名如下:“请填写您的
%{属性}"

Using internationalization for this is probably your best bet. Take a look at

http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

Particularly this section:

5.1.2 Error Message Interpolation

The translated model name, translated
attribute name, and value are always
available for interpolation.

So, for example, instead of the
default error message "can not be
blank" you could use the attribute
name like this : "Please fill in your
%{attribute}"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文