2013-03-21 62 views
1

我想在我的导轨路线URL中使用冒号作为分隔符而不是正斜杠。是否有可能做到这一点?冒号作为Rails路线的分隔符?


我以后类似如下的

match '*page_path/:title ":" *section_path ":" :section_title' => 'pages#show' 

所以对于URL food/fruit/apples:cooking:pie:apple_pie将返回参数:

:page_path = "food/fruit" 
:title = "apples" 
:section_path = "cooking:pie" 
:section_title = "apple_pie" 

在轨这可能吗?

+0

正斜杠有什么问题? – 2013-03-21 12:49:40

回答

0

这里有一个办法:

match 'food/fruit/:id' => 'pages#show' # add constraints on id if you need 

class Recipe < ActiveRecord::Base 
    def self.from_param(param) 
    title, section_path, section_title = extract_from_param(param) 
    # your find logic here, ex: find_by_title_and_section_path_and_section_title... 
    end 

    def to_param 
    # build your param string here, 
    # ex: "#{title}:#{section_path}:#{section_title}" 
    # Beware ! now all your urls relative to this resource 
    # will use this method instead of #id. 
    # The generated param should be unique, of course. 
    end 

    private 

    def self.extract_from_param(param) 
    # extract tokens from params here 
    end 
end 

然后在你的控制器:

@recipe = Recipe.from_param(params[:id]) 

注意,在使用使用内置to_param方法是optionnal。