所以,我正试图想出一种在form_for
中自定义错误消息的方法。在我看来,最优雅的方式是在文本区域内。到目前为止,我尝试的任何方法都完全搞砸了表单。请分享您的想法和方法。
简单形式:
<%= f.label :name, 'Name' %><br>
<%= f.text_field :name, size: 30 %>
<%= f.label :password, 'Password' %><br>
<%= f.password_field :password, size: 30 %>
<%= f.label :password_confirmation, 'Confirm' %><br>
<%= f.password_field :password_confirmation, size: 30 %>
<%= f.submit %>
正如你所看到的,自从我添加了一个初始化程序后,这里没有提到错误:
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
errors = Array(instance.error_message).join(',')
if html_tag =~ /^<label/
html_tag
else
%(#{html_tag}<span class="validation-error"> #{errors}</span>).html_safe
end
end
答案 0 :(得分:1)
我的常见解决方案版本:
辅助方法:
def errors_for(model, attribute)
if model.errors[attribute].any?
content_tag :span, class: 'error' do
attribute.to_s.humanize + " " + model.errors[attribute].to_sentence
end
end
end
观点:
<%= errors_for @user, :name %>
你得到了什么:
"Name can't be blank and is too short (minimum is 2 characters)"
答案 1 :(得分:0)
使用辅助方法
def errors_for(model, attribute)
if model.errors[attribute].present?
content_tag :span, :class => 'error_explanation' do
model.errors[attribute].join(", ")
end
end
end
并且在视野中:
<%= lesson_form.text_field :description %><br />
<%= errors_for @lesson, :description %>
答案 2 :(得分:0)
显示错误消息的另一种方法:
def error_messages_for object
error_content = ''
if object.errors.any?
error_content += content_tag(:div, :id => 'error_explanation', :class => 'alert alert-error') do
content_tag(:h3, "#{pluralize(object.errors.count, "error")} prohibited this #{object.class.name.downcase} from being saved:") +
content_tag(:ul, class: 'unstyled') do
object.errors.full_messages.each do |message|
concat content_tag(:li, "#{message}") if message.present?
end
end
end
end
error_content.html_safe
end
Inside views use this helper:
<%= error_messages_for @sample %>
答案 3 :(得分:0)
还可以使用full_messages_for
:
在你的助手中定义:
def error_message_for(record, field)
record.full_messages_for(field).join(",")
end
如果您不想显示完整信息,可以使用:
record.errors.get(field).join(",")
然后在你看来:
<%= errors_message_for @lesson, :description %>