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

2

11

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.

Shoeblack answered 27/11, 2011 at 13:35 Comment(0)
B
40

.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.

Bummer answered 27/11, 2011 at 13:39 Comment(0)
I
4

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.

Inequity answered 27/11, 2011 at 13:39 Comment(1)
@MichaelDurrant, yes. I assume you are talking about ActiveRecord: api.rubyonrails.org/classes/ActiveRecord/….Snail

© 2022 - 2024 — McMap. All rights reserved.