Rails 3.0.10 before_validation callback not called for associated collection objects

喜欢而已 提交于 2019-12-07 09:38:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!