每天一剂Rails良药之Validating Non-ActiveRecord Objects

对于非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

你可能感兴趣的:(Rails,ActiveRecord,idea)