Rails:错误靠近表单中的特定字段 [英] Rails: Errors close to particular fields in forms

查看:51
本文介绍了Rails:错误靠近表单中的特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向导致错误的字段附近的表单中添加一些错误,这就是我的操作方式:

I am trying to add some errors to a form close to the field that caused the error and here is how I am doing this:

 <%= lesson_form.text_field :description %><br />
  <% unless @lesson.errors[:description].blank? %>
    <span id="error_explanation">
      Description <%= @lesson.errors[:description].join(", ") %>
    </span>
  <% end -%>

  <%= lesson_form.label :category %>
  <%= lesson_form.text_field :category %><br />
  <% unless @lesson.errors[:category].blank? %>
    <span id="error_explanation">
      Category <%= @lesson.errors[:category].join(", ") %>
    </span>
  <% end -%>

我想知道是否有更好的非重复性方法.如您所见,除非每个字段都有错误...,否则我将重复相同的操作.

I would like to know if there is a better an non repetitive way of doing this. As you see I am repeating the same unless errors... for each of the fields.

推荐答案

使用辅助方法:

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 %>

  <%= lesson_form.label :category %>
  <%= lesson_form.text_field :category %><br />
  <%= errors_for @lesson, :category %>
<% end %>

或者您也可以使用 simple_form 这样为您完成所有操作:

Or you could use simple_form which will do it all for you like this:

<%= simple_form_for @lesson do |f| %>
  <%= f.input :description %>
  <%= f.input :category %>
  <%= f.button :submit %>
<% end %>

如果您使用simple_form和 haml ,事情看起来会更整洁:

And if you use simple_form and haml, things look a bit neater:

= simple_form_for @lesson do |f|
  = f.input :description
  = f.input :category
  = f.button :submit

以上内容将在该字段旁边显示错误,并将检测属性的类型并显示适当的输入框(例如,文本,密码,复选框等),所有这些都只需一行简单的f.input.

The above will show the error next to the field and will detect type of the attribute and show the appropriate input box (eg text, password, checkbox etc.), all with one simple line f.input.

这篇关于Rails:错误靠近表单中的特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆