2014-09-25 49 views
1

我仍然努力得到我的驗證錯誤消息顯示沒有出現在它的模型的名稱,我有一個嵌套的模型AnimalImage,我正在執行驗證是否提交了一個文件。模型名稱出現在我的驗證錯誤 - 導軌

def limit_num_of_images 
    if image.size < 1 
    errors.add(:base, "Please add an image") 
    ap(errors.inspect) 
    end 
end 

我在這種情況下得到的錯誤是

Animal images base Please add an image 

所有我想要展示的是

Please add an image 

在控制檯展望errors.inspect的輸出

"#<ActiveModel::Errors:0x007fa0192d1890 @base=#<AnimalImage id: nil, animal_id: nil, image: nil, created_at: nil, updated_at: nil>, @messages={:base=>[\"Please add an image\"]}>" 

所以這些消息是在一個哈希?如果是這種情況,我需要找到一種不顯示密鑰的方式?

最後,在我看來,我正在輸出錯誤信息,像這樣

<% @animal.errors.full_messages.each do |msg| %> 
    <li><%= msg %></li> 
<% end %> 

因此,作爲一個快速解決我創建了一個幫手,只是剔除了文本的第一部分,但這種感覺太哈克和我想知道如何使用Rails做正確

def error_edit(message) 
    msg = message 
    msg.gsub('Animal images base', ' ') 
end 

// View 
<% @animal.errors.full_messages.each do |msg| %> 
    <li><%= error_edit(msg) %></li> 
<% end %> 

回答

1

我認爲這會爲你工作

class Animal < ActiveRecord::Base 
    validate do |animal| 
    animal.errors[:base] << "Please add an image" if animal.image.size < 1 
    end 
end 

我也會建議你看看這個鏈接http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-add

將消息添加到屬性的錯誤消息。

你正在做什麼是添加上稱爲基的屬性,這顯然不是你想有

更新什麼消息::基地]從軌3.您應該使用錯誤移除add_to_base方法代替< <「錯誤」。

+0

我得到一個未定義的方法add_to_base你的答案,但生病的樣子進入鏈接你提供多一點 – Richlewis 2014-09-25 10:39:05

+0

其軌道版本。 。oohhh我的壞,檢查更新 – aelor 2014-09-25 10:40:48

+0

哈哈,我不知道這是怎麼回事,仍然輸出相同的錯誤信息,因爲在問題...確定生病了在時間 – Richlewis 2014-09-25 10:47:02

2

我在我的控制器中有同樣的問題。我知道它不是一個更好的解決方案,但我相信它會給你一個想法。

,請不要使用

errors.add(:base, "Please add an image") 

用戶這個

errors.add(:attribute, "Please add an image") 

<% @animal.errors.each do |key,value| %> 
    <li><%= "#{key.to_s.titleize} #{value}".html_safe %></li> 
<% end %>