[Ruby] Rails render redirect_to

1 minute read

Introduction

This time about the difference between render and redirect_to which are often used in Rails.

render

render determines the view file in the controller and renders it.


render :edit

In this case, the html file corresponding to the view file edit is called.

Call from another controller

It can be called from another controller. In that case, you can pass the full path starting from app/views, so specify the template you want to output with the full path.


render "users/show"

You can call the view template from app/views/users.

Specify any file

It can be specified even if it is outside the current directory.


render "/xxx/apps/user_directory/current/app/views/users/show"

Various description methods

render :edit render action: :edit render “edit” render “edit.html.erb” render action: “edit” render action: “edit.html.erb” render “books/edit” render “books/edit.html.erb” render template: “books/edit” render template: “books/edit.html.erb” render “/path/to/rails/app/views/books/edit” render “/path/to/rails/app/views/books/edit.html.erb” render file: “/path/to/rails/app/views/books/edit” render file: “/path/to/rails/app/views/books/edit.html.erb”

https://railsguides.jp/layouts_and_rendering.html

redirect_to

To instruct the browser to resend the request to another URL. Pass the url you want to redirect to the argument.


redirect_to users_url
redirect_to "http://www.~"

Specify controller


redirect_to controller: :users, action: :edit

redirect to previous page

Redirect the current page to the previous page.

redirect_to :back

Change redirect status code

By default, redirect_to returns HTTP status code 302 to the browser and redirects. If you want to make changes

redirect_to users_path, status: 301

Add message when redirected

redirect_to users_path, notice:'Added

Difference between #render and redirect_to For the process where render specifies the view file and only displays it redirect_to resends the request to another URL and makes the browser work.

The difference between displaying a view file or throwing an http request.

Render can be used to return to the previous screen, acquire data, and display it. redirect_to includes updating and deleting data.

Tags: ,

Updated: