Rails:通过belongs_to保存记录并设置外键

时间:2009-11-19 11:27:16

标签: ruby-on-rails associations belongs-to

有没有更好的方法来编写这段代码?它只是不能和我坐在一起,我觉得我应该已经知道有一些真正的“铁轨”:

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继承。

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

1 个答案:

答案 0 :(得分:0)

这将做你想要的。

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

然而,如果没有其他改变,它对你没有任何好处。由于外键存储在当前模型中,因此如果通过after_create回调创建此关联,ActiveRecord将不会保存更改。将保存新的ParentInUse对象,但不会使用相应的parent_in_use_id更新当前模型的数据库行。

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