跳过有条件的儿童验证

时间:2017-10-31 19:34:09

标签: ruby-on-rails ruby

我有两个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的状态, 但是当score_urlauthor.author_type时,我希望跳过scientist验证。

我尝试过这种方式,但在创建过程中无法找到author

class Book < ActiveRecord::Base
  belongs_to :author

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

这里最好的解决方案是什么?

1 个答案:

答案 0 :(得分: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