1

DataMapper モデルでは、2 つの形式のカスタム検証が可能です: プロパティに固有の検証と、オブジェクト全体の検証です。例えば:

 # 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

2 番目のタイプは、複数のプロパティを含む検証に適していますが、ユーザーにエラーが表示されるという問題もあります。

フォームのページの上部にある特定のプロパティに関連付けられていないすべてのエラーを表示したいのですが、簡単に一覧表示する方法がありません。

プロパティ固有ではないエラーのリストを取得するにはどうすればよいですか?

(私は 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 に答える