I'm new to rails and I don't understand the differences between the use of new+save methods and the create method.
def create @item = Item.new(params[:item]) respond_to do |format| if @item.save format.html { redirect_to @item, notice: 'Item was successfully created.' } format.json { render json: @item, status: :created, location: @item } else format.html { render action: "new" } format.json { render json: @item.errors, status: :unprocessable_entity } end end end
and:
def create respond_to do |format| if Item.create(params[:item]) format.html { redirect_to @item, notice: 'Item was successfully created.' } format.json { render json: @item, status: :created, location: @item } else format.html { render action: "new" } format.json { render json: @item.errors, status: :unprocessable_entity } end end end
Basically the new method creates an object instance and the create method additionally tries to save it to the database if it is possible. Check the ActiveRecord::Base documentation: create method Creates an object (or multiple objects) and saves it to the database, if validations pass.
The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.
create saves to the database and returns true or false depending on model validations. create! saves to the database but raises an exception if there are errors in model validations (or any other error). Follow this answer to receive notifications.
Updates its receiver just like update but calls save! instead of save, so an exception is raised if the record is invalid.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With