2011-03-10 76 views
1

我剛開始使用Rails 3的,我不太明白如何去重新命名路線。Rails 3條中重命名路線

我想要什麼:

到路徑重命名爲users#show控制器/動作對。因此,而不是URL爲www.example.com/users/show/1的這純粹是www.example.com/1/home

在未來,我還希望能夠增加額外的路徑到年底如:

www.example.com/1/home/profile/

我如何用戶資源設置:

resources :users, :except => [:destroy] do 
    resources :favorites, :only => [:show, :update] 
    resources :profiles, :only => [:show, :update] 
end 

我試了一下:

match :home, :to => 'users#show' 

發生了什麼事:

ActiveRecord::RecordNotFound in UsersController#show 

    Couldn't find User without an ID 

是什麼在development.log文件:

Started GET "/home" for 127.0.0.1 at 2011-03-10 13:36:15 -0500 
    Processing by UsersController#show as HTML 
    [1m[35mUser Load (1.6ms)[0m SELECT "users".* FROM "users" WHERE ("users"."id" = 101) LIMIT 1 
Completed in 192ms 

ActiveRecord::RecordNotFound (Couldn't find User without an ID): 
    app/controllers/users_controller.rb:19:in `show' 

什麼是在用戶控制器:

def show 
    @user = User.find(params[:id]) 

    respond_to do |format| 
    format.html # show.html.haml 
    end 
end 

所以,很顯然它是存儲用戶ID,如在開發日誌爲101,但不管是什麼原因,我還是收到此錯誤?

你可以提供任何幫助,不勝感激!

回答

2

你應該在你的比賽提供了一個分段密鑰:

match ':id/home' => 'users#show' 

但有了這個重命名你會得到不REST風格的路線。

另一件事是與用戶配置文件。如果一個用戶只能有一個配置文件,最好聲明奇異資源路線:

resources :users do 
    resource :profile 
end 
+0

這給出了一個路由錯誤:'沒有路由匹配{:controller =>「users」,:action =>「show」}' – iwasrobbed 2011-03-10 19:25:15

+0

它應該工作。你可以顯示你的'耙路線'嗎? – Voldy 2011-03-10 19:37:54

+0

下面是相關的rake路由:https://gist.github.com/864769 – iwasrobbed 2011-03-10 19:43:28

0

我無法解釋爲什麼它正在發出該SQL請求,但它沒有使用101來查找用戶。如果是這樣,你會得到這樣的錯誤:

ActiveRecord::RecordNotFound: Couldn't find User with ID=101 

既然說Coundln't find User without and ID,那麼它可能調用User.find(nil)

總之,我們所做的只是用名稱,而不是標識在我們的應用程序類似的東西。他們在路由文件的底部是匹配的,就像這樣:

match '/:current_region' => 'offers#show', :as => 'region_home' 

,然後在你的控制器,你可以從參數params[:current_region]加載模型:

def load_region 
    @current_region = Region.find_by_slug(params[:current_region] || cookies[:current_region]) 
end 

我們把它作爲一個過濾器很多的動作之前,因此我們定義它像這樣,而不是顯式調用它在show行動:

class OffersController < ActionController::Base 
    before_filter :load_region 

    def show 
     # do stuff with @current_region here 
    end 
end 

你只需要改變:current_region:id

+0

我很抱歉,但作爲新的Rails,因爲我看你的代碼僅僅是困惑我,甚至更多。如果你可以使用我的代碼顯示我,這對我來說會更容易理解。 – iwasrobbed 2011-03-10 19:33:17