Ruby on Rails:你如何为命名路由添加前缀?

sjs*_*jsc 5 ruby ruby-on-rails

我希望生成一个链接,该链接的前缀附加到指定的路由本身.像这样显示路径"/ old/recipes":

recipes_path(:prefix => "old/")  # the correct way should show "/old/recipes"
Run Code Online (Sandbox Code Playgroud)

我不想触摸routes.rb文件,但修改带有前缀的命名路由.这是可能的,你会如何正确地做到这一点?

编辑:我正在使用Rails 3.添加可选前缀的原因是我也想使用普通的recipes_path.所以我想同时使用"/ recipes"和"/ old/recipes".

Rya*_*igg 11

如果你不想触摸路径文件,你会遇到很多痛苦,主要是因为这是Rails在试图弄清楚你的路线去向时会引用的东西.我不知道另一种方法,所以当你确信这是一个好主意时,这是config/routes.rb代码:

scope :path => "old" do
  resources :recipes
end
Run Code Online (Sandbox Code Playgroud)

现在,当你前往recipes_path它的时候会去/old/recipes,虽然这可能不是你想要的.如果是这种情况,那么你可能想要as在这个结尾处scope查看选项:

scope :path => "old", :as => "old" do
  resources :recipes
end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,这条路线现在old_recipes_path仍将路由到/old/recipes.