jordan
jordan

Reputation: 10812

Rails 4 - Creating associated model during update of another model

I am using the Wicked gem to build an instance of a model in steps (step 1, step 2, etc). On the third step, however, I need to make an API call to collect some data and store it in another model instance (it would have a :belongs_to relationship with the other model). What I am wondering is how do I interact with this API and store information, all while I am still in the creation process of the first model. Is this a good design pattern? Or should I be dealing with API information in a different way?

My thoughts are that I could redirect to the form for making the API call and redirect back to the fourth step after dealing with the API.

Does Rails have a specific design it uses for dealing with 3rd party APIs?

Upvotes: 0

Views: 158

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

Although your question was rather verbose, I would recommend looking at the before_create ActiveRecord callback in your model:

#app/models/parent.rb
Class Parent < ActiveRecord::Base
   before_create :build_child
end

This builds the child object before you create the parent, meaning that when you save the parent, you'll have the child created at the same time. This will allow you to create the child object when interacting with the parent. To ensure the child's data is populated correctly, you'll need to use an instance method with the callback

Upvotes: 1

Danny
Danny

Reputation: 6025

No, this is not a good design pattern, but sometimes there is no way around it. Important is that

  1. everything is covered by a single database transaction, and that, as I understand from your question, is the case. Your objects are connected by a "belongs_to" relationship, so they can be saved in one go (when the "parent" object is saved, the "children" will be saved at once). There is also no second, unconnected object involved, so no need to create a separate transaction just for this action

  2. second is that you cover everything with enough error handling. This is your own responsibility: make sure when the 3rd party call goes bananas, you're ready to catch the error, and worse case, roll back the entire transaction yourself

So, to summarize: no it's not a good practice, but Rails gives you the tools to "keep it clean"

Upvotes: 1

Related Questions