[英]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. 我有一个带有嵌套
Customer
模型的Bill
模型。 The Customer
model has a phone number with a uniqueness validation on it. Customer
模型的电话号码具有唯一性验证。 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? 我该如何以
RESTful
方式完成它?
你会使用find_or_create_by方法,在你的情况下看起来像这样:
fetchedRecord = Bill.find_or_create_by_phone_number(customer.phone_number)
You can look at the find_or_create or find_or_create_by methods (which are dynamically created). 您可以查看find_or_create或find_or_create_by方法(动态创建)。 A little Googling should get you there the rest of the way, I think.
我认为,一点点谷歌搜索应该让你在那里完成剩下的工作。
It doesn't seem like these answers are what you are asking. 看起来这些答案似乎不是你所要求的。
Forget about Rails, my question would be, what's the RESTful way to create a resource that might already exist? 忘记Rails,我的问题是,创建可能已经存在的资源的RESTful方法是什么? Should you POST to the resources (list) URL, and then expect a HTTP status code of 201 if the resource was created and a 200 if it already existed?
您应该POST资源(列表)URL,然后如果资源已创建,则期望HTTP状态代码为201,如果已存在则为200?
Seems like this should be spelled out in a standard somewhere. 似乎这应该在标准的某处拼写出来。
By the way, this is how I am handling it--with status codes. 顺便说一句,这就是我处理它的方式 - 使用状态代码。
我把我放在关联回调before_add
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.