我在这里待了几个小时,仍然无法弄清楚。我对嵌套资源控制器上的2个动作进行了2个测试。 requests
是父资源路由,而response
是嵌套资源路由。
这2个测试给了我no route matches
错误。没有道理。在第一个测试中,它将尝试运行update
动作而不是edit
。这是我的测试:
test "should get edit" do
assert_routing edit_request_response_path(@myresponse.request_id, @myresponse), { :controller => "responses", :action => "edit", :request_id => @myresponse.request_id.to_s, :id => @myresponse.id.to_s }
get :edit, params: { id: @myresponse, request_id: @myresponse.request_id }
assert_response :success
end
test "should update response" do
post :update, :request_id => @myresponse.request_id, response: { body: @myresponse.body, request_id: @myresponse.request_id, status: @myresponse.status, subject: @myresponse.subject, user_id: @myresponse.user_id }
assert_redirected_to response_path(assigns(:response))
end
错误如下:
3) Error:
ResponsesControllerTest#test_should_get_edit:
ActionController::UrlGenerationError: No route matches {:action=>"edit", :controller=>"responses", :params=>{:id=>"980190962", :request_id=>"999788447"}}
test/controllers/responses_controller_test.rb:43:in `block in <class:ResponsesControllerTest>'
4) Error:
ResponsesControllerTest#test_should_update_response:
ActionController::UrlGenerationError: No route matches {:action=>"update", :controller=>"responses", :request_id=>"999788447", :response=>{:body=>"This is the body", :request_id=>"999788447", :status=>"draft", :subject=>"This is the subject", :user_id=>"175178709"}}
test/controllers/responses_controller_test.rb:48:in `block in <class:ResponsesControllerTest>'
最佳答案
在这种情况下,您可能要使用浅层嵌套,因为如果可以通过request
进行响应,则没有理由遍历/response/:id
。
resources :requests, shallow: true do
resources :response
end
http://guides.rubyonrails.org/routing.html#nested-resources
test "should get edit" do
assert_routing edit_response_path(@myresponse), { :controller => "responses", :action => "edit", :id => @myresponse.id.to_s }
get :edit, params: { id: @myresponse, request_id: @myresponse.request_id }
assert_response :success
end
但是,命名业务逻辑对象
Request
和Response
是一个很大的错误。这些已经是Rails中的关键概念,它们对应于来自客户端的请求以及通过Rails发送给客户端的响应。您最终会混淆自己和必须在项目上进行工作的任何可怜的傻瓜。另外,您最终将掩盖了
request
和response
方法,它们是ActionController API的重要组成部分。请改用其他一些同义词。