Base

常用方法:

match

mount

root

match 方法

这里的 match 只是个同名方法,是个空壳子,具体实现要看 Resources 里的 match.

另外,mount 和 root 本质上,都是封装和扩展 match 方法。

mount 和 root
      |
      V
    match

mount 方法

挂载一个基于 Rack 的应用到我们的程序。

match '/movies/search', => "movies#search"
# 去掉语法糖,等价
match '/movies/search', => MoviesController.action(:search)

因为 mount 实现基于 match,可以使用相同的可选参数。例如:

现在,你可以通过 exciting_pathexciting_url 访问到刚才挂载的应用。

使用 mount 代替match 还有一个细节不同,在被挂载的 Rack endpoint 里,映射路由时我们不必加前缀。举例:

不是:

而是:

root 方法

实现:

因为 root 实现基于 match,可以使用相同的可选参数。

建议你把 root 放在 config/routes.rb 的开头部分,因为 Rails 的匹配规则是从上至下生成的,会优先匹配。

最后更新于

这有帮助吗?