Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to create an object via an API, i.e. no forms are required, should I be doing MyModel.new(:name => params[:name]) or MyModel.create(:name => params[:name]) ?

Assume I have resources : my_models in routes

I checked and I see that methods can use the params hash ok.

like image 778
Michael Durrant Avatar asked Nov 27 '11 13:11

Michael Durrant


2 Answers

.new makes an instance (but you'll still need to .save it).
while
.create makes an instance and saves it in one go.

Hopefully that helps your decision on which to use.

like image 98
jamiescript Avatar answered Oct 25 '22 13:10

jamiescript


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.

like image 36
WarHog Avatar answered Oct 25 '22 14:10

WarHog