Ruby-on-rails 如何在字段旁边显示错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5646855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:55:24  来源:igfitidea点击:

How to Show Error Messages Next to Field

ruby-on-railsdevisehaml

提问by newbie_86

I have a form with input fields/labels etc. How do I get the error message to show up next to the field? instead of clumped together at the top?

我有一个带有输入字段/标签等的表单。如何让错误消息显示在该字段旁边?而不是在顶部聚集在一起?

I am using devise, rails 3

我正在使用设计,导轨 3

I have this at the top of my form:

我的表格顶部有这个:

 = form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
- if resource.errors.any?
  #errorExplanation
    %h2
      = pluralize(resource.errors.count, "error")
      prevented this user from being saved:
    %ul
      - resource.errors.full_messages.each do |msg|
        %li
          = msg

回答by fl00r

回答by el_quick

Just create a file in your initializers folder.

只需在您的 initializers 文件夹中创建一个文件。

config/initializers/inline_errors.rb

配置/初始化程序/inline_errors.rb

Place this code in it:

将此代码放入其中:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  unless html_tag =~ /^<label/
    %{<div class="has-error">#{html_tag}<span class="help-block">#{instance.error_message.first}</span></div>}.html_safe
  else
    %{#{html_tag}}.html_safe
  end
end

PD: Sorry for my english.

PD:对不起我的英语。

回答by illusionist

How about this

这个怎么样

if you want to put the error message just beneath the text field, you can do like this

如果您想将错误消息放在文本字段下方,您可以这样做

.row.spacer20top
  .col-sm-6.form-group
    = f.label :first_name, "*Your First Name:"
    = f.text_field :first_name, :required => true, class: "form-control"
    = f.error_message_for(:first_name)


What is error_message_for?
--> Well, this is a beautiful hack to do some cool stuff

什么是error_message_for
--> 嗯,这是一个做一些很酷的事情的漂亮技巧

# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
  def error_message_for(field_name)
    if self.object.errors[field_name].present?
      model_name              = self.object.class.name.downcase
      id_of_element           = "error_#{model_name}_#{field_name}"
      target_elem_id          = "#{model_name}_#{field_name}"
      class_name              = 'signup-error alert alert-danger'
      error_declaration_class = 'has-signup-error'

      "<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
      "#{self.object.errors[field_name].join(', ')}"\
      "</div>"\
      "<!-- Later JavaScript to add class to the parent element -->"\
      "<script>"\
          "document.onreadystatechange = function(){"\
            "$('##{id_of_element}').parent()"\
            ".addClass('#{error_declaration_class}');"\
          "}"\
      "</script>".html_safe
    end
  rescue
    nil
  end
end


Resultenter image description here

结果在此处输入图片说明

Markup Generated after error

错误后生成的标记

<div id="error_user_first_name" for="user_first_name" class="signup-error alert alert-danger">This field is required.</div>
<script>document.onreadystatechange = function(){$('#error_user_first_name').parent().addClass('has-signup-error');}</script>

Corresponding SCSS

对应的 SCSS

  .has-signup-error{
    .signup-error{
      background: transparent;
      color: $brand-danger;
      border: none;
    }

    input, select{
      background-color: $bg-danger;
      border-color: $brand-danger;
      color: $gray-base;
      font-weight: 500;
    }

    &.checkbox{
      label{
        &:before{
          background-color: $bg-danger;
          border-color: $brand-danger;
        }
      }
    }

Note: Bootstrap variables used here and, do not forget to Restartthe server now and after any modification to the file in config dir.

注意:这里使用的引导程序变量,不要忘记现在和在对配置目录中的文件进行任何修改后重新启动服务器。

回答by krunal shah

You can use error_message_on http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_message_on

您可以使用 error_message_on http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_message_on

Update:

更新:

form.error_messages was removed from Rails and is now available as a plugin. Please install it with rails plugin install git://github.com/rails/dynamic_form.git.

form.error_messages 已从 Rails 中删除,现在可作为插件使用。请安装它rails plugin install git://github.com/rails/dynamic_form.git