【问题标题】:Rails: Errors close to particular fields in formsRails:靠近表单中特定字段的错误
【发布时间】:2012-03-17 16:13:46
【问题描述】:

我正在尝试将一些错误添加到靠近导致错误的字段的表单中,我是这样做的:

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

我想知道是否有更好的非重复方式来执行此操作。如您所见,我重复相同的内容,除非每个字段都有错误。

【问题讨论】:

    标签: ruby-on-rails forms validation


    【解决方案1】:

    使用辅助方法:

    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,它会像这样为你做这一切:

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

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

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

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

    【讨论】:

    • 开始使用简单的表格。看起来棒极了。谢谢
    • 辅助方法示例有错字,应该是model.errors[而不是mode.errors[
    猜你喜欢
    • 1970-01-01
    • 2013-09-29
    • 2022-01-22
    • 2012-10-05
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多