1

有没有更好的方法来编写这段代码?它只是不适合我,我觉得有一些我应该已经知道的真正“轨道式”的东西:

belongs_to :parent_in_use
belongs_to :parent_template

def after_create
  new_parent_in_use = ParentInUse.create!(self.parent_template.attributes)
  self.update_attribute(:parent_in_use_id, new_parent_in_use.id)
end

创建记录后,我将使用选定的父模板并parent_in_use基于它创建记录。这样模板可以更改,in_use 记录将永远与我的对象一起存在。ParentInUse 和 ParentTemplate 类都使用 STI 从 Parent 继承。

我确定这应该足够简单,但我不知道该怎么做,基本上我想在一次操作中创建并分配记录。

4

1 回答 1

0

这将满足您的需求。

def after_create 
  self.parent_in_use = ParentInUse.create!(parent_template.attributes)
end

但是,如果没有其他更改,它对您没有任何好处。因为外键存储在当前模型中,如果这个关联是由 after_create 回调创建的,ActiveRecord 不会保存更改。新的 ParentInUse 对象将被保存,但当前模型的数据库行不会使用相应的 parent_in_use_id 更新。

将其称为 before_create 回调,事情会更顺利。

于 2009-11-19T17:24:19.977 回答