2017-04-10 12 views
1

我的設計使用我的應用程序正確配置,助手正在努力在字段旁邊顯示單個錯誤消息。目前錯誤顯示爲「不能空白」或「已經被採用」。我想爲它添加一個前綴,例如「用戶名不能爲空」或「已發送電子郵件地址 」,但無法弄清楚。添加前綴來設計錯誤幫助程序

這基本上是我想要的東西來實現,但不起作用

<%= "Username" + errors_for @user, :username %> 

user.rb

def errors_for(model, attribute) 
     if model.errors[attribute].present? 
     content_tag :div, :class => 'error_explanation' do 
      model.errors[attribute].join(", ") 
     end 
     end 
    end 

色器件/註冊/ new.html.erb

<%= f.text_field :first_name, autofocus: true, class: 'form-control', placeholder: 'First name' %> 
    <%= errors_for @user, :first_name %> 
    <br> 
    <%= f.text_field :username, autofocus: true, class: 'form-control', placeholder: 'Username'%> 
    <%= errors_for @user, :username %> 
    <br> 

回答

0

您可以通過以下方式獲取完整的信息:

@user.errors.full_messages_for(:first_name) 
@user.errors.full_messages_for(:username) 

或者使用

@user.errors.full_messages 

得到所有完整的錯誤消息。

您可以在語言文件更改模型字段名稱和錯誤消息:config/locales/**.yml(在devise範圍)。

例子:如果你的程序語言是英語,編輯您config/locales/en.yml

en: 
    activerecord: 
    attributes: 
     user: 
     first_name: "your custom field name" 
    errors: 
     messages: 
     blank: "your custom error message" 

你可以從here獲得更多信息。

希望這會有所幫助。

+0

謝謝,這個工程,但我得到[「名不能空白」],並希望刪除[「」]和樣式的錯誤消息。我怎麼做? – Joshua

+0

我更新了我的答案。希望它有幫助。 – hoangdd