Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails - nested attributes: How to do a find or create of the nested model

I have a Bill model with nested Customer model. The Customer model has a phone number with a uniqueness validation on it. While creating the bill I want to fetch the existing record based on the phone number or create a new one if such doesn't exist. How should I do it in a RESTful way?

like image 515
TMaYaD Avatar asked Jan 06 '10 16:01

TMaYaD


1 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)
like image 122
Patrick Robertson Avatar answered Oct 22 '22 20:10

Patrick Robertson