I have devise configured correctly with my application and the helper is working to display individual error messages next to the fields. Currently the errors appear as "can't be blank" or "has already been taken". I want to add a prefix to it, like "Username can't be blank" or "Email has already been taken" but can't figure out how.
This is basically what I want to achieve but doesn't work
<%= "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
devise/registrations/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 :(得分: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获取更多信息。
希望这有帮助。