2009-07-25 33 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在任何你喜歡的視圖。