2010-09-06 66 views
2

我想在我的路線中使用正則表達式。我有一個產品的控制器,但我希望有一個不同的URL結構來訪問產品高級路由與Rails3

這些URL應該調用一個動作在我的控制器(Products:show_category(:category)

是這樣的可能嗎?

match "(this|that|andthat)" => "products#show_category", :category => $1 

的動作應該是這樣的

def show_category 
    puts params[:category] # <-- "this" if http://host/this/ is called 
    # ... 
end 

回答

3

我沒有實際測試,但嘗試:

match ':category' => 'products#show_category', :constraints => { :category => /this|that|andthat/ } 
+0

太棒了,那完美的作品!感謝提示:constraints-Option – Fu86 2010-09-07 06:26:59

0

我也不太清楚,如果這個回答你的問題,但你可以添加一個集合的routes.rb:

resources :products do 
    collection do 
    get :category1 
    get :category2 
    get :category3 
    end 
end 

如果您運行rake routes,則會看到您有像/products/category1products/category2這樣的網址。組別,2和3可以在控制器中被定義爲平常:

def category1 
    #custom code here 
end 

def category2 
    #custom code here 
end  

def category3 
    #custom code here 
end 

正如我說的,我也不太清楚,如果這就是你希望做什麼,而是希望有點幫助!

+0

我想有一個更聰明的方式來做到這一點。我想指出所有三個網址都指向與類別名稱相同的操作作爲參數。我將這個問題稍微調整一下。 – Fu86 2010-09-06 21:16:17

+0

當然,上面的建議是完美的! – Budgie 2010-09-07 08:17:02