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.
Redirect and render in 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.
redirect_to root_path
redirect_to user_path(@user)
render :edit
render json: { error: 'Not found' }, status: :not_foundThis 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.
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
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.
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.