`

#error_messages_for(*params)

阅读更多
  # Returns a string with a <tt>DIV</tt> containing all of the error messages for the objects located as instance variables by the names
      # given.  If more than one object is specified, the errors for the objects are displayed in the order that the object names are
      # provided.
      #
      # This <tt>DIV</tt> can be tailored by the following options:
      #
      # * <tt>:header_tag</tt> - Used for the header of the error div (default: "h2").
      # * <tt>:id</tt> - The id of the error div (default: "errorExplanation").
      # * <tt>:class</tt> - The class of the error div (default: "errorExplanation").
      # * <tt>:object</tt> - The object (or array of objects) for which to display errors,
      #   if you need to escape the instance variable convention.
      # * <tt>:object_name</tt> - The object name to use in the header, or any text that you prefer.
      #   If <tt>:object_name</tt> is not set, the name of the first object will be used.
      # * <tt>:header_message</tt> - The message in the header of the error div.  Pass +nil+
      #   or an empty string to avoid the header message altogether. (Default: "X errors
      #   prohibited this object from being saved").
      # * <tt>:message</tt> - The explanation message after the header message and before
      #   the error list.  Pass +nil+ or an empty string to avoid the explanation message
      #   altogether. (Default: "There were problems with the following fields:").
      #
      # To specify the display for one object, you simply provide its name as a parameter.
      # For example, for the <tt>@user</tt> model:
      #
      #   error_messages_for 'user'
      #
      # To specify more than one object, you simply list them; optionally, you can add an extra <tt>:object_name</tt> parameter, which
      # will be the name used in the header message:
      #
      #   error_messages_for 'user_common', 'user',bject_name => 'user'
      #
      # If the objects cannot be located as instance variables, you can add an extra <tt>:object</tt> parameter which gives the actual
      # object (or array of objects to use):
      #
      #   error_messages_for 'user',bject => @question.user
      #
      # NOTE: This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what
      # you need is significantly different from the default presentation, it makes plenty of sense to access the <tt>object.errors</tt>
      # instance yourself and set it up. View the source of this method to see how easy it is.
     
def error_messages_for(*params)
        options = params.extract_options!.symbolize_keys

        if object = options.delete(:object)
          objects = Array.wrap(object)
        else
          objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
        end

        count  = objects.inject(0) {|sum, object| sum + object.errors.count }
        unless count.zero?
          html = {}
          [:id, :class].each do |key|
            if options.include?(key)
              value = options[key]
              html[key] = value unless value.blank?
            else
              html[key] = 'errorExplanation'
            end
          end
          options[:object_name] ||= params.first

          I18n.with_options :locale => options[:locale], :scope => [:activerecord, :errors, :template] do |locale|
            header_message = if options.include?(:header_message)
              options[:header_message]
            else
              object_name = options[:object_name].to_s.gsub('_', ' ')
              object_name = I18n.t(object_name, :default => object_name, :scope => [:activerecord, :models], :count => 1)
              locale.t :header, :count => count, :model => object_name
            end
            message = options.include?(:message) ? options[:message] : locale.t(:body)
            error_messages = objects.sum {|object| object.errors.full_messages.map {|msg| content_tag(:li, ERB::Util.html_escape(msg)) } }.join

            contents = ''
            contents << content_tag(options[:header_tag] || :h2, header_message) unless header_message.blank?
            contents << content_tag(:p, message) unless message.blank?
            contents << content_tag(:ul, error_messages)

            content_tag(:div, contents, html)
          end
        else
          ''
        end
      end
分享到:
评论

相关推荐

    django自定义非主键自增字段类型详解(auto increment field)

    default_error_messages = { 'invalid': _("'%(value)s' value must be an integer."), } def __init__(self, *args, **kwargs): kwargs['blank'] = True super(AutoIncreField, self).__init__(*args, **...

    Struts2.0框架技术详解

    &lt;result name="error" type="dispatcher" location="/WEB-INF/jsp/error.jsp" /&gt; ``` #### 六、验证数据的方式 **6.1 使用validate方法验证数据** 通过在Action类中实现`validate()`方法来进行数据验证。 **...

    结合telnet与ftp 功能服务器wasd第三版源码

    [return]: return successfully message,if success, or print error messages error message will be introduced below [eg] : Walle&gt;s /usr/src/qt-embedded-linux-opensource-src-4.4.3.tar.gz send...

    jqGrid增加时--判断开始日期与结束日期(实例解析)

    messages: { "etsadd_startDate": { required: "请输入开始日期", validDateRange: "结束日期不能早于开始日期" }, "etsadd_endDate": { required: "请输入结束日期", validDateRange: "结束日期不能早于...

    JQuery validation plugin学习资料

    return this.optional(element) || (value &gt;= params[0] && value &lt;= params[1]); }, "数值需在{0}和{1}之间"); ``` ### 五、显示与隐藏错误消息 默认情况下,验证插件会在元素失去焦点时显示错误消息。你可以...

    Ruby-attache一个文件上传方式

    render json: { error: @attachment.errors.full_messages }, status: :unprocessable_entity end end def destroy @attachment = Attache::File.find(params[:id]) @attachment.destroy head :no_content ...

    xe10_rest调用发送信息两种参数方式

    RESTRequest.Params.AddItem('data', Params.ToString, pkREQUESTBODY); finally Params.Free; end; RESTRequest.Execute; // 处理响应结果 end; ``` 在这个例子中,参数`param1`和`param2`被封装进一个JSON...

    Rails 3.2:嵌套形式的演示第4部分:切换到目标计算机!

    在Rails 3.2中,我们通常会使用`accepts_nested_attributes_for`方法来定义模型间的嵌套关系。例如,在Ship模型中,我们需要这样写: ```ruby class Ship has_many :pilots accepts_nested_attributes_for :...

    Ruby-Interactor为执行复杂的交互提供了一个公共接口在一个单一的请求

    (error: user.errors.full_messages) end end end ``` 在这个例子中,`context`对象被用来传递数据和状态信息,它是Interactor的核心部分,允许你在交互之间共享数据。如果`perform`方法中的操作成功,你可以将...

    AndroidFirebase:实现Firebase的Android应用

    DatabaseReference myRef = database.getReference("messages"); ``` 2. **读写数据**: 使用`setValue()`方法写入数据,`addValueEventListener()`监听数据变化。 ```java myRef.setValue("Hello, World!"); ...

    Js validation-framework 使用指南和详细配置

    JSValidation提供了丰富的配置选项,如`messages`用于自定义错误消息,`groups`用于合并多个字段的验证结果,`ignore`用于忽略某些字段的验证等。同时,其API如`validate`, `resetForm`和`showErrors`等,可以帮助你...

    vuevalidator是Vuejs的验证器组件

    你可以通过`:error-messages`属性显示错误消息,或者使用`v-if`指令来控制元素的可见性: ```html $v.username.$error"&gt;用户名不能为空且长度至少为6个字符 ``` 3. **自定义验证规则** VueValidator允许你定义...

    validators:可以在浏览器和 Node.js 之间共享的验证器

    ValidationError(messages[, {code: null, params: null}]) 验证错误构造函数。 出于定制目的,除了验证消息之外, ValidationError还可以指定一个code来标识错误的类别以及在适用时插入到验证消息中的任何params ...

    struts2.0中文帮助手册

    例如,`&lt;s:textfield&gt;`用于创建输入字段,`&lt;s:submit&gt;`创建提交按钮,`&lt;s:actionerror&gt;`显示动作错误,`&lt;s:iterator&gt;`遍历集合并渲染其内容。这些标签使得开发者能够以更符合语义化的方式编写JSP页面,提高了代码的...

    AndroidC2DMDemo--客户端代码开发

    sendNotification("Deleted messages on server: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work...

    GENESIS 2000 DFM PE

    having to wait for the R&D department to deliver. These customized features are not added on as scripts to be interpreted slowly but as fully compiled and integrated functions of the system. Once ...

    AngularJS Form 进阶:远程校验和自定义输入项

    通过在`ng-messages`元素中定义不同的消息,我们可以根据表单控件的`$error`属性显示相应的错误信息。 ```html &lt;div ng-messages="myForm.email.$error"&gt; 邮箱是必填的。 请输入有效的电子邮件地址。 ``` ...

    经典小巧的表格组件 EhLib4.14

     If even in this case you will get error messages about TGridDrawState types,  it is necessary to elaborate the name of type by the name of the module.  For instance write GridsEh.TGridDrawState or...

    EhLib-delphi

     If even in this case you will get error messages about TGridDrawState types,  it is necessary to elaborate the name of type by the name of the module.  For instance write GridsEh.TGridDrawState or...

    AngularJS动态校验

    &lt;div ng-messages="myForm.username.$error"&gt; 用户名是必填项。 ``` 5. **自定义表单控件的验证** 如果需要创建自定义表单控件,可以扩展`ngModelController`并重写`$validators`和`$asyncValidators`。...

Global site tag (gtag.js) - Google Analytics