使用ActiveModel :: Validations验证嵌套模型

时间:2016-06-03 01:28:38

标签: ruby-on-rails ruby validation activemodel

我的应用程序使用带有ActiveModel::Validations的普通Ruby类,而没有实现ActiveRecord

class Car
  include ::ActiveModel::Validations

  attr_accessor :engine
end

class Engine
  include ::ActiveModel::Validations

  attr_accessor :cylinders
  validates_presence_of :cylinders
end

我希望Car检查ActiveModel::Validations的嵌套属性,在本例中为engine

car = Car.new
car.engine = Engine.new

car.engine.valid? # => false
car.valid?        # => true
                  # It should return 'false',
                  # because 'engine.cylinders' is 'nil'

获得此行为的最简单方法是什么?

2 个答案:

答案 0 :(得分:3)

一种选择是创建自己的验证方法,例如

class Car
  include ::ActiveModel::Validations

  attr_accessor :engine

  validate :engine_must_be_valid

  def engine_must_be_valid
    errors.add(:base, "Engine is not valid") unless engine.valid?
  end
end

答案 1 :(得分:0)

我在几乎所有项目中都使用Gem active_type来满足类似要求。项目声明 - 使任何Ruby对象像ActiveRecord一样嘎嘎叫。 Project github页面也提供了很好的文档。

在你的Gemfile中

,添加:
gem 'active_type'

然后,

class Car < ActiveType::Object  

    nests_one :engine
    validates :check_engine

    def check_engine
        return true if self.engine.valid?
        false
    end
end

class Engine < ActiveType::Object

    attribute :cylinders, :string
    validates :cylinders, presence: true
end

现在,

car = Car.new
car.engine = Engine.new

car.engine.valid? # => false
car.valid?        # => false