1

DataMapper 模型允许两种形式的自定义验证:特定于属性的验证和整体对象验证。例如:

 # Validates the `name` property with the `check_name` method;
 # any errors will be under `object.errors[:name]`
 validates_with_method :name, method: :check_name

 # Validates the object overall with the `overall_soundness` method;
 # any errors will be under `object.errors[:overall_soundness]`
 validates_with_method :overall_soundness

第二种类型适用于涉及多个属性的验证,但它也存在一个问题:向用户显示错误。

我想在表单页面的顶部显示所有未附加到特定属性的错误,但我没有看到任何简单的方法来列出它们。

如何获取非特定于属性的错误列表?

(我正在使用 DataMapper 1.2.0)

4

2 回答 2

0

一种骇人听闻的方式

我希望有比这更本土的方式。我已将此方法添加到我的模型中:

# Validation errors not tied to a specific property. For instance, 
# "end date must be on or before start date" (neither property is 
# wrong individually, but the combination makes the model invalid)
# @return [Array] of error message strings
def general_validation_errors
  general_errors = []

  general_error_keys = errors.keys.reject do |error|
    # Throw away any errors that match property names
    self.send(:properties).map(&:name).include?(error) || error == :error
  end

  general_error_keys.each do |key|
    general_errors << self.errors[key]
  end

  general_errors.flatten
end

在表单的顶部,我可以这样做:

- if @my_model.general_validation_errors.any?
  .errors
    %ul
      - @my_model.general_validation_errors.each do |error_message|
        %li= error_message

或者,Formtastic 允许的猴子补丁f.general_validation_errors是:

# Let Formtastic forms use f.general_validation_errors to display these (if any)
module Formtastic
  module Helpers
    module ErrorsHelper
      def general_validation_errors
        unless @object.respond_to?(:general_validation_errors)
          raise ArgumentError.new(
            "#{@object.class} doesn't have a general_validation_errors method for Formtastic to call (did you include the module?)"
          )
        end

        if @object.general_validation_errors.any?
          template.content_tag(:div, class: 'errors') do
            template.content_tag(:ul) do
              content = ''
              @object.general_validation_errors.each do |error|
                content << template.content_tag(:li) do
                  error
                end
              end
              content.html_safe
            end
          end
        end
      end
    end
  end
end
于 2012-04-05T21:16:30.800 回答
0

为了显示......你可以使用闪光灯吗?

由于您没有标记一种语言,我将只放置 Ruby 和 Sinatra 的东西,也许您可​​以找到 DSL 等价物。

flash.now[:errors]在您看来,带有相关的条件语句

并在路线中flash[:errors] = User.errors

于 2016-09-09T18:34:50.280 回答