例4
routes.rb
# Example resource route within a namespace:
namespace :admin do
# Directs /admin/test/* to Admin::ProductsController
# (app/controllers/admin/test_controller.rb)
resources :test
end
仔细看
# Directs /admin/test/* to Admin::TestController
# (app/controllers/admin/test_controller.rb)
在controllers创建一个目录admin,在admin下新建一个test_controller.rb。test_controller.rb具体代码见下:
# 一下要把控制器放在Admin::底下
class Admin::TestController < ApplicationController
end
URL
http://ip:host/admin/test
下面这个表比较详细。resources 的表相同,不过前面都加了一个admin
HTTP Verb | Path | action |
---|---|---|
GET | /admin/test | index |
GET | /admin/test/new | new |
POST | /admin/test | create |
GET | /admin/test/:id | show |
GET | /admin/test/:id/edit | edit |
PATCH/PUT | /admin/test/:id | update |
DELETE | /admin/test/:id | destroy |
如果你想要把路由 /test (不以 /admin 作前缀) 匹配到 Admin::TestController,你就需要这样了:
scope :module => "admin" do
resources :test, :comments
end
或者对单个 Resource 匹配的时候
resources :test, :module => "admin"
URL变成
http://ip:host/test 也是可以访问到 TestController中的Action
而你如果想要把路由:/admin/test 给匹配到
TestController (控制器中没有 Admin:: 这个模块作为前缀),你可以用
scope "/admin" do
resources :test
end
或者在为单个 Resource
匹配的时候这么写
resources :test, :path => "/admin/test"
例5
Resources 一起嵌套起来,个人实际开发不会用到,在这就先略过。
resources :publishers do
resources :magazines do
resources :photos
end
end
以上几种比较常用,也比较常见,先到些为止。下面列出几个magic用法吧。
这个路由将会匹配像 /photos/A12345 这样的路由。你可以用如此更简洁的方式来写出这个规则:
match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
重定向
match "/stories" => redirect("/posts")
你同样可以把一条 match 命令中的动态部分的错误处理(rescue)进行重定向
match "/stories/:name" => redirect("/posts/%{name}")
:controller 选项能够让你选择与
resource 关联的控制器。例如:
resources :photos, :controller => "images"
你可以用 :constraints 选项来限定 id 的格式。例如:
resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/}
这个声明限制了 :id 必须与参数里的正则匹配。所以,在这个例子里,路由将不再匹配 /photos/1 ,而只有 /photos/RR27 这样的才会被匹配。你可以用一个代码块来把单个正则限制运用到多条规则上去。
constraints(:id => /[A-Z][A-Z][0-9]+/) do
resources :photos
resources :accounts
end
以上根据一些网上资源和自己的理解,总结。有部分内部是原搬过来。感谢贡献者!