[Ruby] [Sort] To you who are confused by render & redirect_to

1 minute read

Target audience

What is the difference between redirect_to and render? How to use? I know, but those who have not been organized in my head

Prerequisite knowledge

The action in the Rails controller has a mechanism that finally renders and returns a view. In other words, one render always happens for one action.

def index
end

This is the same as rendering’index’ being activated.

Error example

When render is processed twice

def show
  ~~
    if ~~
      ~~
      render'index'
    end
  render'show'
end

The solution is to return

def show
  ~~
    if ~~
      ~~
      render'index'
      return
    end
  render'show'
end

render

A method that specifies the view to call in the action. In other words, **You can call anything other than the view called by default. ** The view format to be called is RHTML format (.html / html.erb etc.)

  • When calling another action view of the same controller

microposts_controller.rb


def index
  render'edit'
  render :edit
end
  • When calling the action view of another controller

microposts_controller.rb


def index
  render "users/show"
  render template: "users/show"
end
  • When calling the action view of another directory or another application

microposts_controller.rb


def index
  render "/warehouse_app/app/views/products/show"
  render file: "/warehouse_app/app/views/products/show"
end

redirect_to

Method that sends a GET request to the specified URL. In other words, if it is activated in the action, **RCV will be called again. **

  • Skip to the specified page

microposts_controller.rb


def index
  redirect_to root_url
end
  • Return to the previous page

microposts_controller.rb


def index
  redirect_back(fallback_location: root_path)
end

I was allowed to reference

Rails guidelines https://railsguides.jp/layouts_and_rendering.html#render%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B

@1ulce https://qiita.com/1ulce/items/282cccba1e44158489c8

@morikuma709 https://qiita.com/morikuma709/items/e9146465df2d8a094d78