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)
答案 0 :(得分: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
答案 1 :(得分:0)
用于显示......你可以使用闪光灯吗?
由于您还没有标记某种语言,我只会放置Ruby和Sinatra的内容,也许您可以找到相应的DSL。
在您的视图中使用相关条件语句 flash.now[:errors]
和路线flash[:errors] = User.errors