[Ruby] Different use of redirect_to and render

less than 1 minute read

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 HTTP requests. render just shows the view (=URL doesn’t change)

When you want to use redirect_to

When data update is successful, run HTTP request and transit to another page. By doing so, reloading will not register the same data.

When you want to use render

If saving fails, just display the view with an error message. Don’t waste your requests. No data has been registered, so there is no problem with reloading.