Proper use of redirect_to and render

Overview

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

Conclusion

redirect_to runs an HTTP request. render just displays the view (= URL doesn't change)

When you want to use redirect_to

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.

When you want to use render

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

Proper use of redirect_to and render
Criteria for proper use of render and redirect_to
Proper use of Mockito and PowerMock
Proper use of interface and abstract class
Difference between redirect_to and render
Difference between redirect_to and render
Difference between render and redirect_to
Difference between render and redirect_to
[rails] Difference between redirect_to and render
[Java8] Proper use of Comparable and Comparator in terms of employee sorting
[Rails] Difference between redirect_to and render [Beginner]
Rails render redirect_to
(Determine in 1 minute) About the proper use of empty ?, blank? And present?
Do you use the for statement after all? Do you use a while statement? Proper use of for statement and while statement
Use of Date class
Use of Japanese fonts and external characters in JasperReport
[Rails] Display error message-Differences between render and redirect_to, flash-
Until the use of Spring Data and JPA Part 2
Until the use of Spring Data and JPA Part 1
Use of Abstract Class and Interface properly in Java
Handling of date and time in Ruby. Use Date and Time properly.
[Rails] Differences between redirect_to and render methods and how to output render methods
Background and mechanism of Fabric-loader
Summary of FileInputStream and BufferedInputStream
Combination of search and each_with_index
Judgment of JSONArray and JSONObject
Use swift Filter and Map
Use @ValueSource of ParametrisedTest of JUnit5
Operator of remainder and exponentiation (exponentiation)
Advantages and disadvantages of Java
[Docker-compose] How to use unnamed and named volumes of volumes. Bind mount
[Rails] Why is it render if save is successful and redirect_to fails?