rails Router后续

本文深入讲解Rails中的路由配置,包括命名空间、资源路由、约束条件等高级特性,并演示如何通过不同方式实现路由映射。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例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
PATCH/PUT,DELETE在上篇大概的讲过,可以参考。

如果你想要把路由 /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

以上根据一些网上资源和自己的理解,总结。有部分内部是原搬过来。感谢贡献者!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值