我希望在父级中包含相当深的关联中的错误:
class Order < ActiveRecord::Base
has_many :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :product, polymorphic: true
end
class Site < ActiveRecord::Base
has_one :line_item, as: :product, autosave: true
validates :domain, presence: true
end
用作:
product = Site.new(domain: nil)
order = Order.new
order.line_items << LineItem.new(product: product)
order.valid? #=> false
product.valid? #=> false
product.errors? #=> { 'domain' => 'cannot be blank' }
是否有一些rails方式或assoc-parameter来产生错误 泡泡起来让我得到:
order.errors #=> { 'domain' => 'cannot be blank' }
换句话说,该协会的最高层, 透明地代理其子女的验证错误?
我知道使用简单的before_validation挂钩,如下所示:
class Order < ActiveRecord::Base
before_validation :add_errors_from_line_items
private
def add_errors_from_line_items
self.line_items.each do |line_item|
line_item.product.errors.each do |field, message|
errors.add(field, message)
end unless line_item.product.valid?
end
end
end
端
但我想知道是否有一些我忽略的ActiveRecord功能。