Rails 3 custom formatted validation errors?

With this model:

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

as a pretty far-fetched example. The error appears as:

Email We need your email address

How can I provide the format myself?

I looked at the source code ActiveModel::Errors#full_messagesand 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

Pay attention to the format string :defaultin the parameters? So I tried:

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

But then the error message actually looks like:

Email something

So, I tried to include the interpolation string %{message}, so overriding the %{attribute} %{message}Rails version by default is used. This throws an exception:

I18n :: MissingInterpolationArgument in SubscriptionsController # create

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

, %{attribute}, , .

- ? , - (- !).

+3
2

: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
+6

All Articles