Ruby 关于 Rails7 中 redirect_to 的一个小问题

2604249649 · 2023年05月01日 · 最后由 2604249649 回复于 2023年05月01日 · 438 次阅读

按道理在 Rails 中这两行代码不应该是等价的么 redirect_to @userredirect_to user_url(@user),但是在我在 Rails7 中使用时,两者重定向地址貌似不一样,不知道是什么原因导致的。

  • redirect_to @user会重定向到http://localhost:3000/users/id

  • redirect_to user_url(@user)会重定向到http://localhost:3000/users.id


部分代码

<%#  用户注册页面 %>
<%= 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
    

有大佬知道这是什么原因导致的么?

if @user.save
  # redirect_to users_url(@user)
  redirect_to @user
else
  render 'new'
end

你注释的代码,写的是 users_url,不是user_url

如一楼说的,用错了方法,复数 users_url 对应的是 index action,单数 user_url 才是 show action

谢谢大佬们提醒,确实是这个问题,下次注意不再犯这种低级错误

2604249649 关闭了讨论。 05月01日 13:34
需要 登录 后方可回复, 如果你还没有账号请 注册新账号