原创作者: hideto   阅读:798次   评论:0条   更新时间:2011-05-26    
对于非ActiveRecord对象的Validation,我们不能简单的include ActiveRecord::Validations
我们需要写一个module,如ValidatingNonARObjects/lib/validateable.rb
module Validateable
  [:save, :save!, :update_attribute].each{|attr| define_method(attr){}}
  def method_missing(symbol, *params)
    if(symbol.to_s =~ /(.*)_before_type_cast$/)
      send($1)
    end
  end
  def self.append_features(base)
    super
    base.send(:include, ActiveRecord::Validations)
  end
end

这样我们就可以对非ActiveRecord对象中使用validations了,如:
class Person
  include Validateable
  attr_accessor :age
  validates_numericality_of :age
end
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics