2012-03-26 47 views
2

我有一條路由將請求路由到somepath/:id(.:format)somecontroller#show將具有特定格式的請求路由到Rails中的不同控制器

這適用於任何格式的每一個請求。但是,我有一個條件,其中somepath/:id.png應該返回一個圖像,並已在othercontroller#show實現該代碼。

我認爲最好是將.png請求路由到othercontroller而不是複製代碼。

實現這個目標的方法是什麼?
我已經考慮過使用約束,但我不確定這是否是正確的方法。

回答

3

我看到的唯一方法是使用

match 'somepath/:id.png' => 'othercontroller#show' 
match 'somepath/:id(.format)' => 'somecontroller#show 

這將路由所有png格式的請求到另一個控制器,和所有其他以somecontroller。

肯定您將PNG路線之前其他。

+1

這非常有效,只需要添加':format =>:png'。唯一的缺點是它沒有強制執行這種格式,所以我實際上可以訪問'somepath/id.png.json'。 – GeReV 2012-03-27 17:53:52

0
match 'photos/:id' => 'photos#show', :defaults => { :format => 'gif' } 

Rails會將Photos/12與PhotosController的show動作匹配,並將params [:format]設置爲「jpg」。

info

相關問題