0
0
Ruby on Railsframework~5 mins

Redirect and render in Ruby on Rails

Choose your learning style9 modes available
Introduction

Redirect and render help control what the user sees next in a web app. Redirect sends the user to a new page, while render shows a specific view without changing the URL.

After a form submission, redirect to a confirmation page to avoid resubmission.
Show an error message on the same page if form data is invalid using render.
Redirect to the homepage after a user logs out.
Render a specific template when loading a page with dynamic content.
Redirect to a login page if a user tries to access a protected page.
Syntax
Ruby on Rails
redirect_to path_or_url
render template_or_options

redirect_to sends a new request to the browser, changing the URL.

render shows a view template without changing the URL or making a new request.

Examples
Sends the user to the homepage URL.
Ruby on Rails
redirect_to root_path
Redirects to the show page of a specific user.
Ruby on Rails
redirect_to user_path(@user)
Renders the edit template for the current controller without redirecting.
Ruby on Rails
render :edit
Renders a JSON response with a 404 status code.
Ruby on Rails
render json: { error: 'Not found' }, status: :not_found
Sample Program

This controller tries to save a new article. If saving works, it redirects to the article's show page. If saving fails (like missing data), it renders the new article form again so the user can fix errors.

Ruby on Rails
class ArticlesController < ApplicationController
  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article
    else
      render :new
    end
  end

  private

  def article_params
    params.require(:article).permit(:title, :content)
  end
end
OutputSuccess
Important Notes

Use redirect_to when you want the browser to load a new page and change the URL.

Use render to show a view template without a new browser request or URL change.

Redirect causes a new HTTP request; render does not.

Summary

redirect_to sends the user to a different URL and triggers a new request.

render shows a view template without changing the URL or making a new request.

Use redirect after successful actions, and render to show forms or errors on the same page.