如何跨模型分享验证?

时间:2012-06-24 16:10:36

标签: ruby-on-rails ruby-on-rails-3

我在模型TipoMovimiento中有这个验证:

class TipoMovimiento < ActiveRecord::Base
  before_validation :default_values

  validates :codigo, :numericality => {:greater_than => 0}
  validates :codigo, :descripcion, :sintetico, :presence => true
  validates :codigo, :descripcion, :sintetico, :uniqueness => true
  validates :descripcion, :length => {:minimum => 3}
  validates :sintetico, :length => {:minimum => 2}

private
  def default_values
    self.estado ||= true if self.estado.nil?
    self.codigo ||= TipoMovimiento.maximum(:codigo) + 1
  end
end

另外,我有其他具有相同字段的模型,我不想在它们上重复这些验证。我是怎么做到的?

2 个答案:

答案 0 :(得分:2)

我认为您应该使用custom validationsinheritance

答案 1 :(得分:2)

我要做的是创建一个单独的模型:

module Validator                                                                                                                                              
  def self.included(base)
    base.send :validates, :name, :presence => true
  end
end

class User < ActiveRecord::Base
  include Validator
end