[Organization] To you who get messed up with render & redirect_to

Target person

What is the difference between redirect_to and render? How to use? Those who know but can't organize in their heads

Prerequisite knowledge

The action in the Rails controller is finally rendered and returns a view. In other words, 1 render ** always occurs for each ** 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 give a return

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

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

--When calling another action view on the same controller

microposts_controller.rb


def index
  render 'edit'
  render :edit
end

microposts_controller.rb


def index
  render "users/show"
  render template: "users/show"
end

microposts_controller.rb


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

redirect_to A 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. ** **

microposts_controller.rb


def index
  redirect_to root_url
end

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

Recommended Posts

[Organization] To you who get messed up with render & redirect_to
What to do if you get angry with OpenSSL with pyenv install
[Rails] What to do if you can't get parameters with form_with
How to get started with slim
How to get along with Rails
Memo to get with Struts2 + Ajax
To you who absolutely need backtrace
If you dare to compare Integer with "==" ...
I tried to get started with WebAssembly
[Note] How to get started with Rspec
[Rails] Give this article to you who looked up in "devise name login"