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. This works completely fine.

Now, I'd like to add user inputted keywords to the Component model via the same form. I've created a separate Keyword model. The issue is that when I'd like to create the Component with references to the relevant keywords that were entered into the form. 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.

My current thought is to handle it in the success callback of the ajax request like:

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

  error: function(data) {


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.

Does that sound reasonable or is there a better way?

Answers 1

  • I would consider looking into the method find_or_create_by, and using it within your Component controller to create any keywords that do not already exist.

Related Articles