映射到Rails的控制器命名空间不一致'路线问题

时间:2014-09-06 07:11:45

标签: ruby-on-rails ruby heroku rails-routing

  concern :votable do
    resources :votes, only: [:index, :create]
  end

  namespace :api, defaults: {format: :json} do
    namespace :v1 do
      namespace :problems do
        resources :details, only: [:index, :show], concerns: :votable

我的routes.rb与上面一样,我将VotesController放在api\v1\votes_controller.rb中。班级名称为Api::V1::VotesController

它在我的本地计算机(Windows 7, ruby 2.0.0p481 (2014-05-08) [i386-mingw32], Rails 4.1.5)上运行正常,但它在Heroku(ruby 2.0.0p481 (2014-05-08 revision 45883) [x86_64-linux], Rails 4.1.5)上的工作方式不同。从日志中,似乎期望VotesController位于api\v1\problems\votes_controller.rb

错误日志:

ActionController::RoutingError (uninitialized constant Api::V1::Problems::VotesController):

它知道bug吗?如果我想让votes_controller.rb不在Api :: V1 :: Problems命名空间内,我该如何配置它?

我希望它是通用的&任何其他控制器都可以重用,所以我避免将它放在api:v1:problems目录下。

1 个答案:

答案 0 :(得分:2)

将您的路线更改为scope而不是namespace

namespace :api, defaults: {format: :json} do
    namespace :v1 do
      scope '/problems' do
        resources :details, only: [:index, :show], concerns: :votable

这应该产生这样的路线:

/api/v1/problems/votes => Api::V1::VotesController

<强>更新

concern :votable do
  resources :votes, only: [:index, :create]
end

namespace :api, defaults: {format: :json} do
  namespace :v1 do
    scope 'problems' do
      resources :details, only: [:index, :show], concerns: :votable, controller: '/problems/details'
    end
  end
end

路线:

$ rake routes|grep 'api'
api_v1_detail_votes GET    /api/v1/problems/details/:detail_id/votes(.:format) api/v1/votes#index {:format=>:json}
                    POST   /api/v1/problems/details/:detail_id/votes(.:format) api/v1/votes#create {:format=>:json}
     api_v1_details GET    /api/v1/problems/details(.:format)                  api/v1//problems/details#index {:format=>:json}
      api_v1_detail GET    /api/v1/problems/details/:id(.:format)              api/v1//problems/details#show {:format=>:json}

这是你正在寻找的吗?