2012-05-07 37 views
0

比方說,我有一個收據模式,我想提供一個控制器動作打印一個......將未寧靜的辦法是做:通過命名空間進行安靜路由的正確約定是什麼?

# receipt_controller.rb 
    def print 
    ... 
    end 

#routes.rb 
    resources :receipts do 
    get :print, :on => :member 
    end 

... REST風格的方法是:

# receipt_printings_controller.rb 
    def create 
    ... 
    end 

#routes.rb 
    resources :receipts 
    resources :receipt_printings, :only => :create 

我的問題是.....比方說,我想有以下結構:

/app 
    /controllers 
    receipts_controller.rb 
    /receipt 
     printings_controller.rb 

這將意味着我的類會是什麼樣子: 一流的收據:: PrintingsController <的ActiveRecord :: Base的 DEF創建 ... 結束 結束

但我不知道如何在這種情況下正確的路線,因爲我還需要能夠做到:

receipt_printings_path(123),以獲得/收據/ 123 /印刷

我知道如何做到這一點的唯一方法是要做到:

#routes.rb 
    match "/receipts/:id/printings" => "receipt/printings#create", :as => :receipt_printings 
    resources :receipts 

但是,我想知道是否有更好的方法?

+0

聽起來像一個問題,應該在http://codereview.stackexchange.com –

回答

0

我認爲你可以做這樣的事情:

resources :receipts do 
    resources :printings, :controller => "receipt/printings", :only => :create 
end 

它會生成:

receipt_printings POST /receipts/:receipt_id/printings(.:format) receipt/printings#create 

然後要訪問您的路線:

receipt_printings_path(:receipt_id => @receipt.id) 

我希望它有幫助

0

如果我是正確的,你需要一個嵌套的資源,有看在這個rails guide

+0

據我所知,一個嵌套的資源將無法與命名空間的控制器...(除非父資源也命名空間,這在這種情況下它不應該是) – patrick

0

你可以使用嵌套路由,但我讀到你的問題的方式聽起來像我想你想要的命名空間。命名空間可能類似於以下內容:

resources :receipts 
namespace :receipts do 
    resources :printings 
end 

這將路線/收據/印刷/:id來應用/收據/ printings_controller.rb與印刷(非收據)的ID。

你可能真的想要嵌套的路線。如果您想使用收據ID,並且只有一個打印操作(每個收據),則可以使用單一資源。

resources :receipts do 
    resource :printing 
end 

這將路由/收據/:ID /打印到應用程序/ printings_controller.rb作爲顯示。

要在命名空間中組織打印控制器,我會將它從路由中排除,因爲它會嘗試在URL中插入另一個收據命名空間。相反,使用,

resources :receipts do 
    resource :printing, :controller => "receipt/printings" 
end 

這是如何成爲RESTful。但是,您可能沒有RESTful案例。印刷是否真的在創造?它真的在做一個節目或更新嗎?如果它是不適合CRUD操作的服務,那麼是時候偏離黃金路徑,繼續使用非RESTful動詞。