关联集合对象未调用Rails 3.0.10 before_validation回调 [英] Rails 3.0.10 before_validation callback not called for associated collection objects

查看:69
本文介绍了关联集合对象未调用Rails 3.0.10 before_validation回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got an object called a Parent that has_many Child objects:

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

子级包含一个指定:before_validation 回调:

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

我注意到,在为孩子创建父级和嵌套属性时,不会为每个Child调用:before_validation 回调。这是预期的行为吗?我试过做一个 before_save 回调,它似乎正常工作。

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.

这是在Rails 3.0上。 10。

This is on Rails 3.0.10.

谢谢!

推荐答案

您应使用 validates_associated

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

这篇关于关联集合对象未调用Rails 3.0.10 before_validation回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆