Rumpleteaser
Rumpleteaser

Reputation: 4234

Rails: Can I create and save an object instance within a class method on a model?

Is it possible and kosher to use a class method on a model to create a new instance of the same model?

The scenario is that I want to interact with an external API, create an instance on the other service, and then once completed successfully store that new object reference in a local model.

So for example I want to call something like this from the controller:

MyModel.interact_with_api_function([variables required])

And have a class method like this on the model:

def interact_with_api([variables required])
  interacts with api, generates object over there, returns result
  This.new(identifier: result, ...).save!
end

Upvotes: 1

Views: 1488

Answers (1)

joshua.paling
joshua.paling

Reputation: 13952

Is it possible and kosher to use a class method on a model to create a new instance of the same model?

Yes, you can do that. In fact, when you do something like MyModel.first, that's exactly what's happening. first is a class method, which fetches a row from the database, creates a new instance of your model, and then populates it with the data fetched from that database call.

The scenario is that I want to interact with an external API, create an instance on the other service, and then once completed successfully store that new object reference in a local model.

If you think of the SQL call to the database as similar to a call to an external API (ie, the database is an external service, like your API), then the situation in the first method is not that unlike what you're doing.

Likewise, the MyModel.create method is a class method, built into Rails, that both creates a new instance of that model, and then saves it to the database - again, not unlike what you're doing.

So, I'd say it's fine.

Upvotes: 1

Related Questions