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 继承。
我确信这应该足够简单,但我不知道该怎么做,基本上我想在一次操作中创建并分配记录。
Is there a better way of writing this code? It just doesn't sit right with me, I feel like there is something really 'rails like' that I should already know:
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
After creating a record I am taking the selected parent template and creating a parent_in_use
record based on it. This way the template can change and the in_use record will live with my object forever. Both the ParentInUse and ParentTemplate classes inherit from Parent using STI.
I'm sure this should be simple enough but I don't know how to do it, basically I would like to create the and assign the record in one operation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将满足您的需求。
然而,如果没有其他改变,它不会给你带来任何好处。由于外键存储在当前模型中,因此如果此关联是由 after_create 回调创建的,则 ActiveRecord 将不会保存更改。新的 ParentInUse 对象将被保存,但当前模型的数据库行将不会使用相应的parent_in_use_id 进行更新。
将其作为 before_create 回调调用,事情会进展得更顺利。
This will do what you're looking for.
However without other changes it won't do you any good. Because the foreign key is stored in the current model, ActiveRecord won't save the change if this association is created by an after_create call back. The new ParentInUse object will be saved, but the database row for the current model will not be updated with that corresponding parent_in_use_id.
Call it as a before_create call back and things will go more smoothly.