What does redirecting to a particular instance mean? I am aware of how the redirecting works.
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
log_in @user
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
def edit
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
I understand the following ways of redirecting:
redirect_to :new
(redirect to new method and displaying the new.html.erb file) redirect_to "show"
(redirect to show.html.erb file or the path for show method) but what does redirect_to @user
mean? Which method and path are we are redirecting to?
If you check the redirect_to documentation, you will find this.
Record - The URL will be generated by calling url_for
with the options
, which will reference a named URL for that record.
It's Rails "magic" for redirecting to the #show
action for that @user
using GET
. You'll find similar things in default Rails forms as well, but for actions like POST
.
According to section 7.4.1 from Michael Hartl's The Rails Tutorial :
redirect_to @user
can be written instead of
redirect_to user_url(@user)
Quoting Michael Hartl:
This is because Rails automatically infers from redirect_to @user that we want to redirect to user_url(@user) .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.