Ruby on rails 3 Rails3到掩码的单一路由:id

Ruby on rails 3 Rails3到掩码的单一路由:id,ruby-on-rails-3,routing,Ruby On Rails 3,Routing,在2.5单一资源下的Rails指南中,它指出 有时候,你有一个资源 客户总是不加掩饰地抬头看 引用ID。例如,您 希望/配置文件始终显示 当前登录的用户的配置文件 用户。在这种情况下,可以使用 要映射/配置文件的单一资源 (而不是/profile/:id)以显示 行动 所以我尝试了这个例子: match "profile" => "users#show" 但是,当我尝试转到profile_路径时,它会尝试重定向到以下位置,其中id=:id: /profile.id 这代表两个问题: 我

2.5单一资源下的Rails指南中,它指出

有时候,你有一个资源 客户总是不加掩饰地抬头看 引用ID。例如,您 希望/配置文件始终显示 当前登录的用户的配置文件 用户。在这种情况下,可以使用 要映射/配置文件的单一资源 (而不是/profile/:id)以显示 行动

所以我尝试了这个例子:

match "profile" => "users#show"
但是,当我尝试转到profile_路径时,它会尝试重定向到以下位置,其中id=:id:

/profile.id
这代表两个问题:

  • 我根本不想显示id,我认为这是一种用于屏蔽id的路由模式
  • 使用此方法会导致以下错误。当我试图请求用户路径时,它也会导致此错误
  • 错误:

    ActiveRecord::RecordNotFound in UsersController#show
    
    Couldn't find User without an ID
    
    我猜这是因为传递的参数如下所示:

    {"controller"=>"users", "action"=>"show", "format"=>"76"}
    
    match "/profile" => "users#show", :as => :profile
    
    我是否正确使用了单一资源

    我的用户控制器:

      def show    
        @user = User.find(params[:id])
    
        respond_to do |format|
          format.html # show.html.erb
          format.xml  { render :xml => @user }
        end
      end
    
    我的路线:

      resources :users
      match "profile"  => "users#show"
    

    它查找:id,因为您的路由文件中可能已经有一个资源配置文件:

    resoruce(s): profile
    
    如果是这样,请尝试将该行移到新行下
    匹配“profile”=>“users#show

    它应该获得较少的优先级,并且应该在读取资源:配置文件之前读取您的新行。


    让我知道这是否是问题所在以及您是否解决了。

    首先,如果您想使用
    profile\u url
    profile\u path
    ,您必须使用
    :如下所示:

    {"controller"=>"users", "action"=>"show", "format"=>"76"}
    
    match "/profile" => "users#show", :as => :profile
    
    你可以找到一个解释

    其次,在控制器中,您依靠
    params[:id]
    查找您要查找的用户。在这种情况下,没有
    params[:id]
    ,因此您必须重写控制器代码:

    def show
      if params[:id].nil? && current_user
        @user = current_user
      else
        @user = User.find(params[:id])
      end
    
      respond_to do |format|
        format.html # show.html.erb
        format.xml  { render :xml => @user }
      end
    end
    


    我是这样做的:

    resources :users
      match "/my_profile" => "users#show", :as => :my_profile
    
    为了使其可行,我还必须编辑控制器代码:

    def show
    
        current_user = User.where(:id=> "session[:current_user_id]")
        if params[:id].nil? && current_user
          @user = current_user
        else
          @user = User.find(params[:id])
        end
    
        respond_to do |format|
          format.html # show.html.erb`enter code here`
          format.xml  { render :xml => @user }
        end
      end
    
    最后,只需提供一个指向我的个人资料的链接:

    <a href="/my_profile">My Profile</a>
    
    
    
    你的
    UsersController#show
    方法是什么样子的?routes.rb中是否还有其他与用户/配置文件有关的路由?提供了包含我的路由和控制器的更新,感谢添加信息。我想你应该让它与我下面的答案一起工作。如果你有更多问题,请告诉我。谢谢你的回复。我没有“配置文件”资源,与“配置文件”匹配的唯一路由是我正在尝试与之匹配的路由。我在“用户”资源下也有匹配路由。