我想在我的rails route url中使用冒号作为分隔符而不是正斜杠。有可能做到这一点吗?
我正在接受以下内容
match '*page_path/:title ":" *section_path ":" :section_title' => 'pages#show'
因此,对于网址food/fruit/apples:cooking:pie:apple_pie
,将返回参数:
:page_path = "food/fruit"
:title = "apples"
:section_path = "cooking:pie"
:section_title = "apple_pie"
这可以在铁轨中使用吗?
答案 0 :(得分: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方法的选项是可选的。