Ruby on rails - nested attributes: how to find or create a nested model

I have a Bill model with a nested Customer model. The Customer model has a unique confirmation phone number. When creating an account, I want to get an existing entry based on a phone number or create a new one if one does not exist. How do I do this with RESTful ?

+6
rest ruby-on-rails nested-attributes
source share
4 answers

you would use the find_or_create_by method, which would look something like this in your case:

 fetchedRecord = Bill.find_or_create_by_phone_number(customer.phone_number) 
+2
source share

You can see the find_or_create or find_or_create_by methods (which are dynamically created). I think a little googling should bring you to the end.

0
source share

These answers seem to be what you are asking for.

Forget about Rails, my question would be, what is a RESTful way to create a resource that may already exist? Should you send a POST to the resource URL (list) and then expect the HTTP 201 status code to be generated, and 200 if it already exists?

It seems like this should be stated in the standard somewhere.

By the way, this is how I handle it - with status.

0
source share

I put mine in the before_add association before_add

0
source share

All Articles