2011-05-09 60 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>