【问题标题】:Basic rails 3 routes and unknown routes (including wildcards)基本铁轨 3 条路线和未知路线(包括通配符)
【发布时间】:2011-11-16 09:45:11
【问题描述】:

我一直在阅读 Rails 3 中的路由,但未能成功实现我的需求。对于 Rails 3 中的路由来说还是相当新的,所以我可能只是忽略了一些事情或者把它复杂化了。

这就是我想要实现的目标:

website/foo 路由到 foo 控制器,index 操作

website/foo/index 路由到 foo 控制器,index 操作

website/foo/bar 路由到 foo 控制器,bar 操作

website/foo/random 路由到 foo 控制器,index 操作

website/foo/bar/rondom 路由到 foo 控制器,bar 操作

其中“随机”可以是任何文本、数字、路径 (/new/x/w/y/23) 或其他任何内容。

我尝试将matchresourcescollection 一起使用,虽然它处理了基本情况,但它没有处理“随机”。

我也在寻找各自的命名路径,应该指定还是会生成?

【问题讨论】:

  • rake routes 将显示存在的命名路由。

标签: ruby-on-rails ruby-on-rails-3 routing routes rails-routing


【解决方案1】:

您正在寻找route globbing

foo/bar/*additional => "foo#bar" 

例子:

website/foo/bar/random # params[:additional] = "random"
website/foo/bar/random/2 # params[:additional] = "random/2"
website/foo/bar/random/and/more/1/random/stuff/ # params[:additional] = "random/and/more/1/random/stuff/"

【讨论】:

  • 我对这条评论无能为力。请提供你的 routes.rb 文件,我去看看。
  • 我正在尝试这个,但出现错误。 match 'foo/*other' => 'foo#index', :as => 'foo#index' match 'foo/bar/*other' => "foo#bar', :as => 'foo#bar' 给出错误:ActionController::RoutingError Exception: /usr/local/lib/ruby/gems/1.8/gems/actionpack-3.0.9/lib/action_dispatch/routing/route_set.rb:425:in 'raise_routing_error': No route matches {:controller=>"foo"} 尽管 foo 控制器存在
  • @baash05 - 虽然它确实链接到外部信息,但它也提供了一个非常清晰的用法示例。我也忍不住注意到您对这里也链接到外部信息的其他答案不太警惕。
【解决方案2】:

http://guides.rubyonrails.org/routing.html 包含大量非常有用的信息,尤其是route globbing 部分。

要完全匹配您在上面定义的内容,您可以:

# config/routes.rb
namespace :website do
  match 'foo'             => 'foo#index'
  match 'foo/index'       => 'foo#index'
  match 'foo/bar'         => 'foo#bar'
  match 'foo/*random'     => 'foo#index' # params[:random] will contain "hello/world" if the URL is /website/foo/hello/world
  match 'foo/bar/*random' => 'foo#bar'
end

您可以使用:as 选项指定命名路由,例如

match 'foo' => 'foo#index', as: 'foo' # helper would be website_foo_path

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2019-12-09
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多