Rails:自定义嵌套控制器操作
我想设置自定义嵌套控制器操作,但我无法弄清楚路由。
我一直收到以下错误
No route matches [GET] "/assets"
的routes.rb
resources :companies do resources :requests do match :accept end end
index.html.rb
- "requests", :action => "accept", :id => request.id %>
存在一些问题:路由到accept
操作并构建到嵌套资源的URL。
定义自定义操作
您可以使用以下语法向RESTful资源添加自定义操作:
resources :requests do get 'accept', :on => :member end
这将为您提供如下所示的路线:
requests/:id/accept
您可以使用以下方法在视图中生成路径:
accept_request_path(a_request)
:on => :member
部分表示您将路由到每个单独请求的新操作,而不是所有请求的集合。 如果您使用:on => :collection
则路由将是requests/accept
嵌套资源
嵌套资源时:
resources :companies do resources :requests do get 'accept', :on => :member end end
您获得的结果如下所示,请注意,由于请求嵌套在公司内部,因此路由包括company_id
和id
:
companies/:company_id/requests/:id/accept
和这样的助手:
accept_company_request_path(a_company, a_request)
您可以像目前正在尝试的那样,通过以下方式做到这一点:
<%= link_to "Accept", :controller => "requests", :action => "accept", :id => request.id, :company_id => request.company.id %>
但是使用助手更容易:
<%= link_to "Accept", accept_company_request_path(request.company, request) %>
适当的动词
接受声音很像是以某种方式更新数据库的东西,如果是这种情况,你应该考虑使用PUT
请求而不是GET
请求。
HTTP / 1.1规范说已经建立了这样的约定:GET和HEAD方法不应该具有采取除检索之外的动作的重要性 ( RFC2616,第9节 ),其具有非人类Web客户端的真实含义 -搜索引擎索引器,浏览器扩展等 – 允许跟踪链接(发出GET
请求)但不允许提交发出其他类型请求的表单。
如果您切换到使用PUT
请求,那么button_to
帮助程序button_to
上用场。 与link_to
您可以将路由所需的控制器,操作,方法和所有参数传递给button_to
:
<%= button_to 'Accept', {:controller => :requests, :action => :accept, :company_id => request.company, :id => request}, :method => :put %>
或者您可以使用帮助程序生成更容易的路径:
<%= button_to 'Accept', accept_company_request_path(request.company, request), :method => :put %>
更多文档
- 添加更多RESTful操作
- 嵌套资源
在您的路线文件中:
match 'request/accept/:id' => 'requests#accept', :as => :accept
在视野中
link_to "Accept", accept_path(request)