简体   繁体   English

ruby on rails,创建新对象,使用create或new方法?

[英]ruby on rails, creating new object, use create or new method?

I am trying to create an object via an API, ie no forms are required, should I be doing MyModel.new(:name => params[:name]) or MyModel.create(:name => params[:name]) ? 我试图通过API创建一个对象,即不需要表单,我应该做MyModel.new(:name => params[:name])还是MyModel.create(:name => params[:name])

Assume I have resources : my_models in routes 假设我有resources : my_models routes resources : my_models

I checked and I see that methods can use the params hash ok. 我查了一下,我看到方法可以使用params hash ok。

.new makes an instance (but you'll still need to .save it). .new创建一个实例(但你仍然需要.save它)。
while
.create makes an instance and saves it in one go. .create创建一个实例一次性保存。

Hopefully that helps your decision on which to use. 希望这有助于您决定使用哪个。

It depends on what are you want to get. 这取决于你想要得到什么。 new method simply instantiates new object and create method creates an object and saves it to the database, if validations pass. new方法只是实例化新对象,如果验证通过, create方法会创建一个对象并将其保存到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM