我有两个ActiveRecords Author
和Book
。
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
验证了name
和score_url
的状态,
但是当score_url
为author.author_type
时,我希望跳过scientist
验证。
我尝试过这种方式,但在创建过程中无法找到author
。
class Book < ActiveRecord::Base
belongs_to :author
validates :name, presence: true
validates :score_url, presence: true, if: "author.scientist?"
end
这里最好的解决方案是什么?
答案 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