2009-07-25 84 views
0

说我有以下型号:如何在这种情况下创建更有意义的错误消息?

class Information < ActiveRecord::Base 
... 
validates_length_of :name, :minimum=>3, :message=>"should be longer than 3 characters!" 
... 

我想有作为的错误是:
信息应长于3个字符!(或相似)
和NOT “信息名称应该超过3个字符!”

两个可能的解决方法我已经看了:

  1. human_attribute_name方法(提到here):不符合我的Rails 2.3.2的工作。 :-(
  2. 直接做information.errors.add "","..." if information.name.length < 3然而,这消除由validated_length_of方法,如特殊类标签引发许多有用的特性(用于着色的东西红色)

任何想法谢谢。? 。您的时间

回答

2

我想你通过full_messages方法,它是为控制台,不显示错误为Web应用程序使用。您应该使用error_message_onerror_messages_for辅助程序(请参阅documentation以获取更多信息),它允许您自定义错误消息。

例子:

<%= error_message_on "information", "name", :prepend_text => 'Information ' %> 
1

不使用轨道帮手,使错误的,通常我有内嵌错误,所以是这样的:

def inline_error_block(obj, meth, prepend="", append="", klass="error error-form", &block) 
    content = capture(&block) 
    obj = (obj.respond_to?(:errors) ? obj : instance_variable_get("@#{obj}")) 
    if obj 
    errors = obj.errors.on(meth.to_s) 
    if errors 
     output = content_tag(:div, :class => klass) do 
     content_tag(:p, "#{prepend}#{errors.is_a?(Array) ? errors.first : errors}#{append}", :class => "error-msg clearfix") + content 
     end 
     return concat(output) 
    end 
    end 
    concat(content_tag(:div, content, :class => "no-error")) 
end 

往往可以做到这一点,但是,它只在每个表单字段中显示一个错误,如果您需要,您肯定可以重新排列它以显示它们。 (errors.first to errors.each)。

要获得全名,只要你想只写与字段名的消息也显示:

validates_length_of :name, :minimum=>3, :message=>"Information should be longer than 3 characters!" 
+0

感谢您的帮助。在我的系统上,底线显示为:信息名称信息应该超过3个字符! :( – jacob 2009-07-26 08:37:55

+0

是使用errors_for或使用我的帮手? – 2009-07-26 10:51:01

+0

你是对的,谢谢。 – jacob 2009-07-29 13:26:32

1

你总是可以设置你的:消息为空字符串的模式然后设置:prepend_text在任何你喜欢的视图。