2011-05-09 58 views
2

在Rails的指导下2.5奇异资源,它指出掩盖Rails3中奇异路线:ID

Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like /profile to always show the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action.

所以,我想这个例子:

match "profile" => "users#show" 

然而,当我试图去到profile_path,它尝试重定向到以下,其中id =:id:

/profile.id 

这表示两个问题:

  1. 我不想在所有显示的ID,并认为这是一个路由模式来掩盖一个id
  2. 使用此方法使下面的错误。当我尝试请求user_path时,它也会导致此错误。

错误:

ActiveRecord::RecordNotFound in UsersController#show 

Couldn't find User without an ID 

我想这是因为通过这个样子的传递的PARAMS:

{"controller"=>"users", "action"=>"show", "format"=>"76"} 

我是否正确使用奇异的资源呢?

我UsersController:

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" 
+0

什么是你的'UsersController#show'方法是什么样子? routes.rb中是否有其他路线与用户/配置文件有关? – Mischa 2011-05-09 08:30:14

+0

提供包含我的路线和控制器的更新 – Coderama 2011-05-09 08:50:06

+0

感谢您添加信息。我认为你应该在下面回答我的问题。如果你有更多的问题,请告诉我。 – Mischa 2011-05-09 09:08:34

回答

2

或者

get "/profile/:id" => "users#show", :as => :profile 
# or for current_user 
get "/profile" => "users#show", :as => :profile 

resource :profile, :controller => :users, :only => :show 
2

它寻找一个:

resoruce(s): profile 
:ID,因为很可能你已经在你的路由文件具有资源概况

如果是这样,请尝试在新行下移动该行match "profile" => "users#show

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

让我知道是否它是问题,如果你解决。

+0

感谢您的回复。我没有“个人资料”资源,唯一匹配“个人资料”的路线是我尝试使用的路线。我在'用户'资源下面也有匹配路线。 – Coderama 2011-05-09 08:37:28

4

首先,如果你想使用profile_urlprofile_path你必须使用:as这样的:

match "/profile" => "users#show", :as => :profile 

你可以找到一个解释here。其次,在你的控制器中,你依靠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 
+0

'get“/ profile”...'在这里会更好 – fl00r 2011-05-09 09:41:13

0

我这样做:

resources :users 
    match "/my_profile" => "users#show", :as => :my_profile 

and to m AKE它可行的,我必须得修改我的控制器代码:

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 

,并在年底只是给一个链接到my_profile:

<a href="/my_profile">My Profile</a>