哈克方式
我希望能有比這更原始的方式。我已經添加了這個方法我的模型:
# 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
或者您也可以按名稱挑你的特殊的錯誤,比如'special_overall_soundness'你的看法。 「validates_with_method」的文檔鼓勵您一次使用一個屬性/方法。 – ujifgc 2012-04-05 21:29:32
或者,如果你想讓你的代碼在DataMapper 1.3上中斷,你可以通過'Model.validators.contexts [:default] .select {| k | k.kind_of? DataMapper :: Validations :: MethodValidator}' – ujifgc 2012-04-05 21:46:48
@ujifgc - 我**一次一個驗證一個驗證,但我想將它們全部列在一個地方供用戶使用。我已經在表單字段旁列出了特定於字段的錯誤;我希望這些其他人都在頂部列表中。另外,'Model.validators.context [:default] .select {| k | k.kind_of?(DataMapper :: Validations :: MethodValidator)'返回所有驗證,不區分字段特定和其他。它們每個都有'field_name'屬性,但是'general'驗證在那裏沒有nil;它們有自己的名字,所以這對我沒有幫助。 – 2012-04-09 16:00:07