代码之家  ›  专栏  ›  技术社区  ›  Anton S.

Ruby on Rails中的路由冲突

  •  4
  • Anton S.  · 技术社区  · 7 年前

    我正在与 Devise gem 我创造了一个 show 用户页面。我的想法是创建一条简单的路径,如 www.website.com/:id 我对其进行了如下配置:

      devise_for :users, path: '', path_names: {sing_in: "login", sing_out: 
         "signout", sing_up: "signup", edit: "edit"}, 
         :controllers => {:registrations => :registrations }
      resources :users, only: [:show]
      get '/:id' => 'users#show', as: :profile
    

    我的路线很好,但除此之外 显示 页面,我有页面在下面 static controller 例如 about 页我希望能够像这样访问它 www.website.com/about ,以下是我如何定义 static routes :

    get '/about', to: 'static#about'
    

    现在,如果我试图重定向到 about page ,我收到一个错误:

    ActiveRecord::RecordNotFound in UsersController#show
    Couldn't find User with 'id'=about
    

    这是我的 users_controller.rb :

    class UsersController < ApplicationController
    
      def show
        @user = User.find_by_id(params[:id])
        @services = @user.services
      end
    
      ...
    end
    

    我试图搜索类似的错误,但没有发现类似的错误。有人能告诉我我做错了什么吗?

    谢谢你的帮助和时间。

    1 回复  |  直到 7 年前
        1
  •  7
  •   Daniel Westendorf    7 年前

    这里有两件事:

    • 路由不知道参数类型
    • 路线自上而下匹配

    在这种情况下,我怀疑您的单级路由正在定义您的 get '/:id' 路线因此,该路由正在捕获以下所有请求: /anything 因为路由器认为 anything 是一个参数。

    只需将您的路线定义移动到任何其他 /about etc路径,以便首先匹配它们。

    这样地:

    get '/about', to: 'static#about'
    get '/:id' => 'users#show', as: :profile