Rails嵌套控制器-错误:没有路线匹配

时间:2018-10-31 13:49:36

标签: ruby-on-rails routes rspec-rails

轨道5.2.1 RSpec 3.8

我正在尝试使用嵌套控制器构建REST API。我遇到错误:

No route matches {:action=>"index", :controller=>"playlists/playlist_items", :format=>:json, :playlist=>60}

这是我的路线。rb:

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :playlists do
    resources :playlist_items, controller: 'playlists/playlist_items'
  end
  resources :playlist_items
  resources :artists
  resources :tracks
end

这是rake routes的输出:

                   Prefix Verb   URI Pattern                                                                              Controller#Action
  playlist_playlist_items GET    /playlists/:playlist_id/playlist_items(.:format)                                         playlists/playlist_items#index
                          POST   /playlists/:playlist_id/playlist_items(.:format)                                         playlists/playlist_items#create
   playlist_playlist_item GET    /playlists/:playlist_id/playlist_items/:id(.:format)                                     playlists/playlist_items#show
                          PATCH  /playlists/:playlist_id/playlist_items/:id(.:format)                                     playlists/playlist_items#update
                          PUT    /playlists/:playlist_id/playlist_items/:id(.:format)                                     playlists/playlist_items#update
                          DELETE /playlists/:playlist_id/playlist_items/:id(.:format)                                     playlists/playlist_items#destroy
... etc ...

这是失败的测试:

describe Playlists::PlaylistItemsController do
  describe "GET #index" do
    before do
      @playlist =  create :playlist, { date: '2000-01-01' } 
      get :index, params: { playlist: @playlist.id, format: :json }
    end
    it "returns http success" do
      expect(response).to have_http_status(:success)
    end
  end
end

该错误抱怨没有路由匹配

{:action=>"index", :controller=>"playlists/playlist_items", :format=>:json, :playlist=>60}

但据我所知rake routes的这一行完全匹配:

  playlist_playlist_items GET    /playlists/:playlist_id/playlist_items(.:format)                                         playlists/playlist_items#index

我想念什么?

1 个答案:

答案 0 :(得分:1)

该参数称为playlist_id而不是playlist

describe Playlists::PlaylistItemsController do
  describe "GET #index" do
    before do
      @playlist =  create :playlist, { date: '2000-01-01' } 
      get :index, params: { playlist_id: @playlist.id, format: :json }
    end
    it "returns http success" do
      expect(response).to have_http_status(:success)
    end
  end
end

请注意,控制器应返回401 CREATED响应。

您还可以通过添加module选项在模块中嵌套资源:

resources :playlists do
  resources :playlist_items, module: :playlists
end