问题
I've got an object called a Parent that has_many Child objects:
has_many :children
accepts_nested_attributes_for :children, :allow_destroy => true
Child includes a Module that specifies a :before_validation callback:
def self.included base
base.class_eval do
before_validation :my_callback
end
end
protected
def my_callback
logger.debug "see me!"
end
I've noticed that when creating a Parent and nesting attributes for children, the :before_validation callback is not being invoked for each Child. Is this the intended behavior? I've tried doing a before_save callback instead and it appears to work fine.
This is on Rails 3.0.10.
Thanks!
回答1:
You should use validates_associated:
class Parent < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children, :allow_destroy => true
validates_associated :children
end
来源:https://stackoverflow.com/questions/8128313/rails-3-0-10-before-validation-callback-not-called-for-associated-collection-obj