About the ActiveRecord method create
that creates a new record.
I learned about the difference between create
and create!
, so I will explain it.
What is the difference with and without !
?
Conclusion "Whether to raise an exception"
.
However, it is difficult to understand the "exception".
To explain the difference that actually occurs, what changes with or without !
is "Is that red screen appearing?"
When processing fails.
create!
If you set create!
, If you get caught in validation, an ActiveRecord :: RecordInvalid exception will occur as shown below, and the familiar screen will be displayed.
Let's follow the actual operation.
The code used this time is as follows (* The description of create action is not recommended).
app/config/routes.rb
Rails.application.routes.draw do
root to: 'comments#index'
resources :comments, only: [:create]
end
app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def index
@comments = Comment.all.order("created_at DESC")
@comment = Comment.new
end
def create
#Writing this create action is deprecated.
@comment = Comment.create!(comment_params)
redirect_to root_path
end
private
def comment_params
params.require(:comment).permit(:text)
end
end
create (new + save)
create
app/models/comment.rb
class Comment < ApplicationRecord
validates :text, presence: true
end
The error screen was displayed firmly.
!
Submit the form for the create action below.
app/controllers/comments_controller.rb
def create
@comment = Comment.create(comment_params) # !Exclude
redirect_to root_path
end
The error screen does not occur due to exception handling, and you are redirected.
!
of create!
is a description that raises an exception!
, the next redirect will be executed as it is without being saved.Recommended Posts