2010-03-26 58 views
2

我想修復我的網站生成的一些錯誤消息。這裏的問題是:ActiveRecord驗證...自定義字段名稱

class Brand < ActiveRecord::Base 
    validates_presence_of :foo 
    ... 
end 

我的目標是做一個信息「票務描述需要」,而不是「foo是必需的」或不能爲空,或者別的什麼東西。

這是如此重要的原因是因爲讓我們先前說這個領域是ticket_summary。這真是太棒了,服務器被編碼使用它,但現在由於瘋狂的瘋狂業務分析人員已經確定ticket_summary是一個可憐的名字,應該是ticket_description。現在我不一定希望我的數據庫受用戶對字段名稱的需求驅動,尤其是因爲它們可以在不更改功能的情況下頻繁更改。

有沒有提供這種機制?

要澄清

:消息=>似乎並沒有被正確的解決方案,:消息會給我「富[消息]」的錯誤,我期待改變生成的字段名消息,而不是實際的信息本身(儘管我會解決不得不改變整個事情)。

回答

7

因此,答案是很簡單...

定義

self.human_attribute_name(attribute)並返回人類可讀的名字:

def self.human_attribute_name(attribute) 
    if attribute == :foo 
     return 'bar' 
    end 
end 

我會使用地圖,當然名字。那就是那個。

+0

這是一個很好的解決方案。我的解決方案是非常通用的,它允許您更改語言環境文件中的消息及其格式,而不是Ruby代碼。 –

+1

如果該屬性不是:foo,您是否需要在最後調用super? – cmrichards

+0

大,但這種方法在軌道4,5兩個參數,做這樣: 高清self.human_attribute_name(attribute_key_name,選擇= {}) 情況attribute_key_name 時:FOO 回報 「酒吧」 其他 回報超(attribute_key_name,選項) 結束 結束 –

7

添加到您的config/locales/en.yml文件:

en: 
    activerecord: 
    errors: 

     # global message format 
     format: #{message} 

     full_messages: 
     # shared message format across models 
     foo: 
      blank: Ticket description is required 

     # model specific message format 
     brand: 
      zoo: 
      blank: Name is required 

現在改變你的驗證消息指新的消息格式:

validates_presence_of :bar, :message => "Empty bar is not a good idea" 
validates_presence_of :foo, :message => "foo.blank" 
validates_presence_of :zoo, :message => "brand.zoo.blank" 

讓我們試着代碼:

b = Brand.new 
b.valid? 
b.errors.full_messages 
#=> ["Ticket description is required", 
#  "Empty bar is not a good idea", 
#  "Name is required"] 

如上所示,您可以在三個級別自定義錯誤消息格式。

1)全球所有的ActiveRecord錯誤消息

activerecord: 
    errors: 
     format: #{message} 

2)在模型之間共享錯誤消息

activerecord: 
    errors: 
     full_messages: 
     foo: 
      blank: Ticket description is required 

3)模型的特定消息

activerecord: 
    errors: 
     full_messages: 
     brand: 
      zoo: 
      blank: Name is required 
+0

這不是問題。該消息將是「+ Foo +這是我的自定義錯誤消息」。我需要「+ Bar +這是我的自定義錯誤消息」爲foo字段。 –

+0

我已經更新了我的答案,這應該滿足您的需求。看一看。 –

+0

請參閱我的答案,以獲得更簡單的解決方案:P –

0

你可以做如下:

# config/locales/en.yml 
en: 
    activerecord: 
    attributes: 
     brand: 
     foo: "Ticket description" 
    errors: 
     models: 
     brand: 
      attributes: 
      foo: 
       blank: " is required" 

請檢查Fully custom validation error message with Rails瞭解更多詳情。