2013-03-21 51 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。