ActiveRecord的 - 更换模型验证错误与警告 [英] ActiveRecord - replace model validation error with warning
问题描述
我希望能够用一个警告保存/更新的铁轨模型时更换现场错误。基本上我想只写周围会产生错误的验证方法的包装,保存模型也许可以提供一个警告哈希(它的工作原理就像错误哈希):
I want to be able to replace a field error with a warning when saving/updating a model in rails. Basically I want to just write a wrapper around the validation methods that'll generate the error, save the model and perhaps be available in a warnings hash (which works just like the errors hash):
class Person < ActiveRecord::Base
# normal validation
validates_presence_of :name
# validation with warning
validates_numericality_of :age,
:only_integer => true,
:warning => true # <-- only warn
end
>>> p = Person.new(:name => 'john', :age => 2.2)
>>> p.save
=> true # <-- able to save to db
>>> p.warnings.map { |field, message| "#{field} - #{message}" }
["age - is not a number"] # <-- have access to warning content
任何想法如何,我可以实现这个?我能增加:警告=&GT;假
默认值的ActiveRecord ::验证:: ClassMethods :: DEFAULT_VALIDATION_OPTIONS
通过扩展模块,但是我正在寻找如何落实剩下的一些见解。谢谢你。
Any idea how I could implement this? I was able to add :warning => false
default value to ActiveRecord::Validations::ClassMethods::DEFAULT_VALIDATION_OPTIONS
By extending the module, but I'm looking for some insight on how to implement the rest. Thanks.
推荐答案
我不知道这是否是准备好Rails 3中,但这个插件确实你在找什么:
I don't know if it's ready for Rails 3, but this plugin does what you are looking for:
http://softvalidations.rubyforge.org/
编辑补充:
要更新这与加载ActiveModel的基本功能,我想出了以下内容:
To update the basic functionality of this with ActiveModel I came up with the following:
#/config/initializer/soft_validate.rb:
module ActiveRecord
class Base
def warnings
@warnings ||= ActiveModel::Errors.new(self)
end
def complete?
warnings.clear
valid?
warnings.empty?
end
end
end
#/lib/soft_validate_validator.rb
class SoftValidateValidator < ActiveModel::EachValidator
def validate(record)
record.warnings.add_on_blank(attributes, options)
end
end
它增加了一个新的错误像称为对象的警告和一个辅助方法的完成?的,你可以把它添加到模型,像这样
It adds a new Errors like object called warnings and a helper method complete?, and you can add it to a model like so:
class FollowupReport < ActiveRecord::Base
validates :suggestions, :soft_validate => true
end
这篇关于ActiveRecord的 - 更换模型验证错误与警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!