轨道:通过belongs_to的保存记录和设置外键
-
21-09-2019 - |
题
有没有写这个代码的一个更好的办法?它只是不跟我坐的权利,我觉得有一些真正的导轨上,如“我已经应该知道:
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从父继承。
我敢肯定这应该是很简单,但我不知道怎么做了,基本上我想创建并在一次操作中分配的记录。
解决方案
这会做你要找的东西。
def after_create
self.parent_in_use = ParentInUse.create!(parent_template.attributes)
end
但是没有其他的变化不会对你有任何好。由于外键存储在当前模型中,如果这种关联是通过after_create调用创建回的ActiveRecord不会保存更改。新ParentInUse对象将被保存,但当前模型数据库行不会与对应parent_in_use_id被更新。
称其为一个before_create回调,事情会更加顺利。
不隶属于 StackOverflow