按道理在 Rails 中这两行代码不应该是等价的么
redirect_to @user
和redirect_to user_url(@user)
,但是在我在 Rails7 中使用时,两者重定向地址貌似不一样,不知道是什么原因导致的。
redirect_to @user
会重定向到http://localhost:3000/users/id
redirect_to user_url(@user)
会重定向到http://localhost:3000/users.id
部分代码
turbo_frame_tag
)<%# 用户注册页面 %>
<%= provide(:title, "Sign up") %>
<h1>Sign up</h1>
<div class="row">
<div class="col-md-6 mx-auto">
<%= turbo_frame_tag "post" do %>
<%= form_for(@user, url: signup_path) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name, class: "form-label" %>
<%= f.text_field :name, class: "form-control" %>
<%= f.label :email, class: "form-label mt-3" %>
<%= f.email_field :email, class: "form-control" %>
<%= f.label :password, class: "form-label mt-3" %>
<%= f.password_field :password, class: "form-control" %>
<%= f.label :password_confirmation, "Confirmation", class: "form-label mt-3" %>
<%= f.password_field :password_confirmation, class: "form-control" %>
<div class="d-grid gap-1 mt-4">
<%= f.submit "Create my account", class: "btn btn-outline-primary" %>
</div>
<% end %>
<% end %>
</div>
</div>
UsersController.rb
def create
@user = User.new(user_params)
# respond_to do |format|
# if @user.save
# # redirect_to @user
# format.html { redirect_to @user, notice: 'User account was successfully created.' }
# format.json { render :show, status: :created, location: @user }
# else
# # 处理注册失败的情况
# format.html { render :new }
# format.json { render json: @user.errors, status: :unprocessable_entity }
# end
# end
if @user.save
# redirect_to users_url(@user)
redirect_to @user
else
render 'new'
end
end
routes.rb
Rails.application.routes.draw do
# Defines the root path route ("/”)
root "static_pages#home"
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
#用户注册路由
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
resources :users
end
有大佬知道这是什么原因导致的么?