我正试图在Rails模式下干掉一些代码。
我有4个验证器,我试图通过使用define_method来干涸,但它无法正常工作。您可以在下面看到我的尝试以及下面的原始方法。 充其量我没有得到验证,最糟糕的是我得到了:
未定义的局部变量或方法`validate_weight'
class Product < ActiveRecord::Base
PRODUCT_DIMENSION_FIELDS = [:weight, :height, :width, :depth]
....
PRODUCT_DIMENSION_FIELDS.each do |meth|
#define_method('validate_' + meth.to_s) do
# errors.add(meth, "can't be blank") if has_parents? && meth.empty?
#end
#define_singleton_method('validate_' + meth.to_s) do
# errors.add(meth, "can't be blank") if has_parents? && meth.empty?
#end
#self.class.send(:define_method, ('validate_' + meth.to_s).to_sym) do
# errors.add(meth, "can't be blank") if has_parents? && meth.empty?
#end
end
# attempting to dry up these methods
def validate_weight
errors.add(:weight , "can't be blank") if has_parents? && weight.empty?
end
def validate_height
errors.add(:height , "can't be blank") if has_parents? && height.empty?
end
def validate_width
errors.add(:width , "can't be blank") if has_parents? && width.empty?
end
def validate_depth
errors.add(:depth , "can't be blank") if has_parents? && depth.empty?
end
end
有没有人有任何想法?
答案 0 :(得分:0)
为什么不使用普通的在线验证器?
class Product < ActiveRecord::Base
PRODUCT_DIMENSION_FIELDS = [:weight, :height, :width, :depth]
validates_presence_of *PRODUCT_DIMENSION_FIELDS, if: :has_parents?
end