简体   繁体   English

创建两个相互依赖的模型的实例

[英]Creating instances of two models that depend on each other

I have a javascript form that creates an ajax POST request that ultimately results in a new instance of a model Component . 我有一个可创建ajax POST请求的JavaScript表单,该请求最终导致模型Component的新实例。 This works completely fine. 这完全正常。

Now, I'd like to add user inputted keywords to the Component model via the same form. 现在,我想通过相同的表单将用户输入的关键字添加到Component模型中。 I've created a separate Keyword model. 我创建了一个单独的Keyword模型。 The issue is that when I'd like to create the Component with references to the relevant keywords that were entered into the form. 问题是,当我想使用对输入到表单中的相关关键字的引用创建Component时。 I can't just assume that all of the entered keywords exist so there is some amount of processing I need to do before updating the references. 我不能仅仅假设所有输入的关键字都存在,所以在更新引用之前我需要做一些处理。 That is, I need to find out which keywords do not exist, put them into the database, and then I can finally create the Component with appropriate keyword references. 也就是说,我需要找出存在的关键字,并将它们放入数据库中,然后最终可以使用适当的关键字引用创建Component

My current thought is to handle it in the success callback of the ajax request like: 我目前的想法是在ajax请求的成功回调中处理它,例如:

$.ajax({
  method: 'POST',
  data: {component:data},
  dataType:'JSON',
  success: function(data) {
   //handle it here...


  }.bind(this),
  error: function(data) {

  }.bind(this)
})

and then iterate through the keywords, create the keywords that don't yet exist, and then add all of the keywords to the component using another POST request. 然后遍历关键字,创建尚不存在的关键字,然后使用另一个POST请求将所有关键字添加到组件中。

Does that sound reasonable or is there a better way? 听起来合理还是有更好的方法?

我会考虑研究一下find_or_create_by方法,并在Component控制器中使用它来创建任何尚不存在的关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM