我是 Rails 的新手,我一直在学习教程。
我一直在摆弄routes.rb,现在完全混淆了它何时寻找show方法以及何时寻找index方法(如果没有明确提及)?
最佳答案
路由就像类固醇上的正则表达式。它们按定义的顺序具有优先级,并与您添加的请求方法、URI 和任何其他约束相匹配。
get '/posts', to: 'posts#index'
get '/posts/:id', to: 'posts#show'
上述路由的关键区别在于请求uri的路径必须匹配的正则表达式不同。
'/posts/:id'
包含一个匹配的命名段:GET /posts/11
GET /posts/gobligook
但不是:
GET /posts
GET /posts/1/foo
GET /posts/foo/bar
完整的常规 CRUD 动词集是:
get '/posts', to: 'posts#index' # all posts
get '/posts/new', to: 'posts#new' # form to create a post
post '/posts', to: 'posts#create' # create a post from a form submission
get '/posts/:id', to: 'posts#show' # show a single post
get '/posts/:id/edit', to: 'posts#edit' # form to edit a post
put '/posts/:id', to: 'posts#update' # for legacy compatibility
patch '/posts/:id', to: 'posts#update' # update a post from a form submission
delete '/posts/:id', to: 'posts#destroy' # delete a post
在 Rails 风格的 REST 中, Action 是从路径和方法隐式派生的。
只有用于呈现表单的 新 和 编辑 方法实际上显式地在路径中添加了操作 - 这是因为它们作用于集合或集合的成员。
请注意,
'/posts/new'
路由必须在 get '/posts/:id'
之前声明,否则 show 路由将首先匹配请求(路由按定义的顺序具有优先级)。这不适用于 get '/posts/:id/edit'
,因为模式不同。当然,输入所有这些路由真的很乏味,所以 rails 提供了
resources
macro 为你做这件事:resources :posts
关于ruby-on-rails - rails 什么时候在 Controller 中查找 Index 方法,什么时候查找 show 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46114272/