没有为关联的集合对象调用Rails 3.0.10 before_validation回调

时间:2011-11-14 21:24:00

标签: ruby-on-rails activerecord

我有一个名为Parent的对象has_many Child对象:

has_many :children
accepts_nested_attributes_for :children, :allow_destroy => true

Child包含一个指定:before_validation回调的模块:

def self.included base
  base.class_eval do
    before_validation :my_callback
  end
end

protected
def my_callback
   logger.debug "see me!"
end

我注意到在为子项创建Parent和嵌套属性时,不会为每个Child调用:before_validation回调。这是预期的行为吗?我尝试过进行before_save回调,看起来效果很好。

这是在Rails 3.0.10上。

谢谢!

1 个答案:

答案 0 :(得分:7)

您应该使用validates_associated

class Parent < ActiveRecord::Base
  has_many :children
  accepts_nested_attributes_for :children, :allow_destroy => true
  validates_associated :children
end