如何在Rails中使用instance_eval子句删除验证? [英] How to remove validation using instance_eval clause in Rails?
问题描述
我想使用instance_eval增强现有的类。原始定义包含验证,该验证要求存在某些字段,即:
I would like to enhance existing class using instance_eval. There original definition contains validation, which require presence of certain fields, ie:
class Dummy < ActiveRecord::Base
validates :field, :presence => true
end
现在,我想使用instance_eval(或任何其他方法)将其更改为可选,真的):
Now I want to change that to optional using instance_eval (or any other method, really):
Dummy.instance_eval do
...
end
删除验证的正确语法是什么,因此该字段是可选的。我宁愿直接在模型层上执行此操作,而不是在控制器或视图中执行奇怪的操作。并不是真正需要使用instance_eval,但是据我所知,这通常是在Rails中增强类的最佳方法。
What would be the proper syntax to remove the validation, so the field is optional. I would rather do this directly on the model layer, instead doing weird hacks in controllers or views. The use of instance_eval is not really required, but as far as I know, this is generally the best way to enhance classes in Rails.
编辑#1
通常-原始类是gem的一部分,我不想分叉它,也不想绑定到特定版本。一般原因并不重要。简单地编辑原始模型比猴子修补的后果要糟得多。
In general - the original class is part of the gem and I don't want to fork it, nor tie to specific release. The general cause is not really important. Simply editing the original model has far worse consequences than monkey patching.
推荐答案
我找到了一个解决方案,不确定它的可靠性如何,但是对我来说效果很好。 @aVenger实际上很接近他的答案。只是 _validators
访问器仅包含用于反射的信息,而不包含实际的验证器回调!它们包含在 _validate_callbacks
访问器中,不要与 _validations_callbacks
混淆。
I found a solution, not sure how solid it is, but it works well in my case. @aVenger was actually close with his answer. It's just that the _validators
accessor contains only information used for reflection, but not the actual validator callbacks! They are contained in the _validate_callbacks
accessor, not to be confused with _validations_callbacks
.
Dummy.class_eval do
_validators.reject!{ |key, _| key == :field }
_validate_callbacks.reject! do |callback|
callback.raw_filter.attributes == [:field]
end
end
这将删除:field
的所有验证器。如果要更精确,可以拒绝 _validators
的特定验证器,该验证器与 raw_filter
访问器相同验证回调的数量。
This will remove all validators for :field
. If you want to be more precise, you can reject the specific validator for _validators
which is the same as the raw_filter
accessor of validate callbacks.
这篇关于如何在Rails中使用instance_eval子句删除验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!