2009-11-19 64 views
1

有没有写这个代码的一个更好的办法?它只是不跟我坐的权利,我觉得有一些真正“像Rails的,我应该已经知道:Rails的:通过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继承。

我敢肯定这应该是很简单,但我不知道怎么做了,基本上我想创建并在一次操作中分配的记录。

回答

0

这将做你在找什么。

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

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

把它作为一个before_create回调,事情会更加顺利。

+0

我想成为100%确信current_model创建相应的记录之前就已经存在。如果模型无效,我认为它不会进入before_create回调? – tsdbrown 2009-11-19 17:51:18

+1

这是一个有效的假设。同样,所有的回调函数都被封装在单个事务中,如果它们中的任何一个返回false或者引发错误,则整个事务被回滚。因此,除非一路上的所有内容成功,否则不会创建ParentInUse。 – EmFi 2009-11-19 18:01:05

相关问题