2017-10-31 20 views
0

私は2つの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 

Booknamescore_urlの両方に存在することを検証します が、私はauthor.author_typescientistときscore_urlの検証をスキップします。

この方法で試しましたが、作成中にauthorが見つかりませんでした。

class Book < ActiveRecord::Base 
    belongs_to :author 

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

ここで最適な解決策は何ですか?

答えて

1

あなたはあなたの検証が任意のより複雑な取得する場合、あなたは新しいメソッドにロジックを抽出する必要がありProc

条件の検証に
validates :score_url, presence: true, if: Proc.new { |book| book.author.scientist? } 

を提供する必要があります。

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

private 

def author_scientist? 
    author.present? && author.scientist? 
end