路径在中定义config/routes.rb。通常使用resourcesorresource方法将它们定义为一组相关的路线。
resources :users创建以下七个路线,所有路线都映射到的动作UsersController:
get '/users', to: 'users#index' post '/users', to: 'users#create' get '/users/new', to: 'users#new' get '/users/:id/edit', to: 'users#edit' get '/users/:id', to: 'users#show' patch/put '/users/:id', to: 'users#update' delete '/users/:id', to: 'users#destroy'
之后的动作名称显示#在to以上参数。具有相同名称的方法必须app/controllers/users_controller.rb按以下方式定义:
class UsersController < ApplicationController def index end def create end # 继续所有其他方法... end
您可以限制使用only或生成的操作except:
resources :users, only: [:show] resources :users, except: [:show, :index]
您可以通过运行以下命令在任何给定时间查看应用程序的所有路由:
$ rake routes
$ rake routes # 要么 $ rails routes
users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format) users#new edit_user GET /users/:id/edit(.:format) users#edit user GET /users/:id(.:format) users#show PATCH /users/:id(.:format) users#update PUT /users/:id(.:format) users#update DELETE /users/:id(.:format) users#destroy
要仅查看映射到特定控制器的路由:
$ rake routes -c static_pages static_pages_home GET /static_pages/home(.:format) static_pages#home static_pages_help GET /static_pages/help(.:format) static_pages#help
$ rake routes -c static_pages static_pages_home GET /static_pages/home(.:format) static_pages#home static_pages_help GET /static_pages/help(.:format) static_pages#help # 要么 $ rails routes -c static_pages static_pages_home GET /static_pages/home(.:format) static_pages#home static_pages_help GET /static_pages/help(.:format) static_pages#help
您可以使用-g选项搜索路线。这显示了与助手方法名称,URL路径或HTTP动词部分匹配的所有路由:
$ rake routes -g new_user # 匹配辅助方法 $ rake routes -g POST # 匹配HTTP Verb POST
$ rake routes -g new_user # 匹配辅助方法 $ rake routes -g POST # 匹配HTTP Verb POST # 要么 $ rails routes -g new_user # 匹配辅助方法 $ rails routes -g POST # 匹配HTTP Verb POST
此外,rails在开发模式下运行服务器时,您可以访问一个网页,该网页显示带有搜索过滤器的所有路由,其优先级从上到下匹配,位于<hostname>/rails/info/routes。它看起来像这样:
帮手 | HTTP动词 | 路径 | 控制器#动作 |
---|---|---|---|
路径/网址 | [路径匹配] | ||
users_path | 得到 | /users(.:format) | 用户#索引 |
开机自检 | /users(.:format) | users#create | |
new_user_path | 得到 | /users/new(.:format) | 用户#新 |
edit_user_path | 得到 | /users/:id/edit(.:format) | 用户#编辑 |
user_path | 得到 | /users/:id(.:format) | 用户#显示 |
补丁 | /users/:id(.:format) | 用户#更新 | |
放 | /users/:id(.:format) | 用户#更新 | |
删除 | /users/:id(.:format) | users#destroy |
使用方法resource而不是resourcesin可以声明路由仅对成员(不是集合)可用routes.rb。使用时resource,index默认情况下不会创建路由,只有在明确要求这样的路由时:
resource :orders, only: [:index, :create, :show]