Forbes magazine logo Ranked Best Coding Bootcamps 2023

.new vs. .save v.s. .create

Altcademy Team wrote on 7 February 2018

In Ruby On Rails, active record provides .new & .save v.s. .create, what is the difference?

Answer

Although it is correct that create calls new and then save there is a big difference between the two alternatives in their return values.
Save returns either true or false depending on whether the object was saved successfully to the database or not. This can then be used for flow control as per the first example in the question above.

Create will return the model regardless of whether the object was saved or not. This has implications for the code above in that the top branch of the if statement will always be executed even if the object fails validations and is not saved.

If you use create with branching logic you are at risk of silent failures which is not the case if you use new + save.

The create alternative can be useful in controllers where respond_with is used for API (JSON/XML) responses. In this case the existence of errors on the object will cause the errors to be returned in the response with a status of unprocessable_entity, which is exactly what you want from an API.

I would always use the new + save option for html, especially if you are relying on the return value for flow control.

Trusted by

Students and instructors from world-class organizations

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #96

Enroll for December 2nd, 2024