2017-10-31 1 views
0

두 개의 ActiveRecords AuthorBook이 있습니다.조건으로 자녀 확인을 건너 뛰십시오.

class Author < ActiveRecord::Base 
    has_many :books 

    enum author_type: { 
    musician: 0, 
    scientist: 1 
    } 

    accepts_nested_attributes_for :books 
end 

class Book < ActiveRecord::Base 
    belongs_to :author 

    validates :name, presence: true 
    validates :score_url, presence: true 
end 

지금 Book 모두 namescore_url, 에 대한 존재의 유효성을 검사하지만 author.author_typescientistscore_url에 대한 검증을 생략 할 수 있습니다.

이 방법을 시도했지만 생성 중에 author을 찾을 수 없습니다.

class Book < ActiveRecord::Base 
    belongs_to :author 

    validates :name, presence: true 
    validates :score_url, presence: true, if: "author.scientist?" 
end 

가장 좋은 해결책은 무엇입니까? 유효성 검사가 더 복잡해 경우

답변

1

당신은 조건부 검증에

validates :score_url, presence: true, if: Proc.new { |book| book.author.scientist? } 

Proc를 제공해야합니다, 당신은 새로운 방법으로 논리를 추출한다.

validates :score_url, presence: true, if: :author_scientist? 

private 

def author_scientist? 
    author.present? && author.scientist? 
end 
관련 문제