2016-06-03 5 views
1

내 응용 프로그램 ActiveRecord을 구현하지 않고, ActiveModel::Validations와 일반 루비 클래스를 사용 :이 경우 engine에, ActiveModel::Validations의있는 중첩 된 속성을 확인 Car 싶습니다검증 중첩 된 모델

class Car 
    include ::ActiveModel::Validations 

    attr_accessor :engine 
end 

class Engine 
    include ::ActiveModel::Validations 

    attr_accessor :cylinders 
    validates_presence_of :cylinders 
end 

.

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

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

이 동작을 얻는 가장 쉬운 방법은 무엇입니까?

답변

2

하나의 옵션은 내가 유사한 요구 사항에 대한 거의 모든 내 프로젝트에 보석 active_type를 사용

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 
+0

나는 어쩌면 내가에 둥지 engine''에서 오류를 원한다고 생각했다 그런
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 

, '자동차'의 실수지만, 대부분의 사람들이 그것이 반 패턴이라고 생각하는 것처럼 보인다. 이것은 내가 작업하고있는 기본 경우에는 충분하다고 보입니다. –

1

처럼 자신의 검증 방법, 뭔가를 만드는 것입니다. 프로젝트 문 - Ruby 객체를 ActiveRecord처럼 돌립니다. Project github 페이지는 좋은 문서를 제공합니다. 당신의 Gemfile에

, 추가

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

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