after_create,belongs_to和validate_presence_of

时间:2011-01-21 12:05:15

标签: ruby-on-rails validation activerecord

我有以下两个类,其中A类在after_create中初始化B.不幸的是,这不起作用,并且由于违反了presence_of验证而导致B的创建失败:

class A < ActiveRecord::Base
  has_many :bs

  after_create :after_create_hook

  def after_create_hook
    B.create(:a => self)
  end
end

class B < ActiveRecord::Base
  belongs_to :a
  validates_presence_of :a
end

创建A时,会创建A,但不会创建B.

1 个答案:

答案 0 :(得分:1)

我刚发现:http://blog.teksol.info/2006/03/08/don-t-validate-belongs_to-or-else

这里的错误是,验证一个实例。由于这只是一个外键,验证必须检查:

validates_presence_of :a_id

现在情况正常。