If you use scaffold
in Rails, the create action will be as follows.
When saving is successful, redirect_to
is used, and when page transition fails, render
is used.
I will explain this difference.
user_cocntroller.rb
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
redirect_to runs an HTTP request. render just displays the view (= URL doesn't change)
When the data update is successful, an HTTP request is executed to move to another page. By doing so, the same data will not be registered by reloading.
If saving fails, just display the view with an error message. Avoid unnecessarily increasing requests. Since the data has not been registered, there is no problem even if it is reloaded.
Recommended Posts