[英]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.