3

使用此模型:

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},它不会出错,它只是两次吐出人性化的属性名称。

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

4

2 回答 2

6

错误 on: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
于 2011-05-22T09:02:11.867 回答
4

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

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

特别是本节:

5.1.2 错误信息插值

翻译后的模型名称、翻译后的属性名称和值始终可用于插值。

因此,例如,代替默认错误消息“不能为空”,您可以使用如下属性名称:“请填写您的 %{attribute}”

于 2011-05-22T09:04:47.087 回答