2010-09-06 69 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