文章目录
1.Routes是什么
- 定义:规定了特定格式的URL请求到后端controller的action的分发规则
- 路由查找是自上而下的,不存在覆盖的情况
- 表现形式:
get 'users/:id' ,to: 'users/show'
get 'users/:id' => 'users/show'
2.命名路由
get 'users/:id' ,to: 'users/show',as: 'user'
- user_path(user) 只要当前传进来的这个模型中有id,rails 会自动解析出来它当前的id
- user_path(user.id)
- user_url
在view 或者controller中需要调用这个路由,需要给它加上_path
或者_url
,_path
为相对地址(eg:/users/2),_url
为绝对地址(eg:http://localhost:3000/users/2)
3.RESTful资源设计
●GET
●POST
●PUT | PATCH
●DELETE
定义每个请求URL的请求方式,同一个URL可以拥有不同的请求方式,也就是说只有请求路由相同,请求方式也相同,请求的资源才是相同的
- RESTful只是约束
- 让我们的代码设计更统一
- 让我们专注于产品实现,而不是代码设计本身
4.resources资源
resources: controller名称
配置一个resources 可以生成7个路由
运行rake routes
可看出当前项目下的所有路由,
5.单数资源
有时候我们不需要传递用户id,如用户自身信息编辑页面,id等信息可以直接从cookie中拿到,不需要传递参数则需要我们自己重新定义一条路由或者使用resource,此时的路由可以看到都是单数url
get 'profile' => 'users/show'
resource :users
6.namespace 关键字
在URL显示admin + controller 把代码放在admin的命名空间中
namespace :admin do
resources :users
end
7.Scope关键字
controller 把代码放在admin的命名空间中(不在URL显示admin)
- 多个资源的定义
scope module:'admin' do
resources :users
end
- 单个资源的定义
resources :users, module: 'admin'
- 在url中显示/admin( controller 不把代码放在admin的命名空间中)
scope '/admin' do
resources :users
end
8. 嵌入路由
在路由中显示用户和博客的对应关系,可以更清晰的判断当前是哪个用户的那篇博客,让路由看起来更有逻辑
resources :users do
resources :blogs
end
注:嵌入式路由最多可以定义一级,不建议嵌入太多,路由过长且传入参数太多。
9.排除不需要的action和请求方式
resources :users, only:[ :index ,:destroy]
10.添加自定义的restful路由
路由划分
- 需要id 的是member,对具体某一个资源的操作
- 不需要id 的是collection,对集合的操作
resources :users do
member do
post :status
end
collection do
get :online
end
end
- 添加自定义的restful路由,也可以通过关键字on单个定义
resources :users do
post :status, on::member
get :online, on::collection
end
11.非资源式路由
get ' : controller(/ :action(/ :id) )
action 和 :id可选的,故路由可以有以下几种:
/photos/show/ 1
/photos/show
/photos # => index actionget: controller/ :action/ :id/ :user id'
路由需要完全匹配
/photos/show/1/2- match 匹配:
match 'photos',to: 'photos#show',via:[:get,:post]
:get,:post的请求,都会匹配到该路由上
- constraints 约束
get 'photos/:id',to: 'photos#show',constraints:{id:/[A~Z]\d{5}/}
photos/A12345 以A~Z之间的字母开头,结尾是5
- redirect 重定向
get'stories',to:redirect('articles')
重定向到新的路由
- mount
当项目非常大,需要做模块拆分时使用
mount AdminApp, at:'/admin'
12.根路由
root_path
root to:'welcome#index'
root 'welcome#index'
13.controller
对某一个controller的路由,进行定义
controller :welcome do
get'welcome/index'
post'welcome/create'
end