【问题标题】:Rails namespaced routes to wrong ControllerRails 命名空间路由到错误的控制器
【发布时间】:2013-05-28 17:34:53
【问题描述】:

所以我只是从 RoR 开始,我想我也写一个带有 API 端点的基本博客。问题是我的 api 请求似乎被路由到了错误的控制器,

我的 routes.rb 有以下内容

Blog::Application.routes.draw do

  namespace :api do
    namespace :v1 do
      resources :articles
    end
  end

end

我也有controllers/api/v1/articles_controller.rb,内容如下:

module API
  module V1    
    class ArticlesController < ApplicationController
      respond_to :json

      def index
        respond_with Article.all
      end

    end
  end
end

我的逻辑是,当我点击http://localhost:3000/api/v1/articles 时,这应该是要响应的控制器,但是响应的实际控制器是控制器根中的控制器 (controllers/articles_controller.rb),而不是 /api/v1 中的控制器小路。当我删除实际响应的控制器时,我会得到uninitialized constant Api::V1::ArticlesController

即使rake routes 给了我预期的路线,但实际上击中这些端点失败了。 rake routes 的输出如下:

api_v1_articles GET    /api/v1/articles(.:format)          api/v1/articles#index
                    POST   /api/v1/articles(.:format)          api/v1/articles#create
 new_api_v1_article GET    /api/v1/articles/new(.:format)      api/v1/articles#new
edit_api_v1_article GET    /api/v1/articles/:id/edit(.:format) api/v1/articles#edit
     api_v1_article GET    /api/v1/articles/:id(.:format)      api/v1/articles#show
                    PUT    /api/v1/articles/:id(.:format)      api/v1/articles#update
                    DELETE /api/v1/articles/:id(.:format)      api/v1/articles#destroy

我在 SO 上发现的唯一类似问题是 nested namespace route going to wrong controller 但是,那里没有公认的答案,已经一年了。也许另一种尝试将有助于解决此问题

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2


    【解决方案1】:

    您的模块是API,但Rails 正在寻找Api。 Ruby 的模块区分大小写。

    【讨论】:

    • 我自己从来没有注意到这一点。谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-05-14
    • 2012-03-07
    • 2016-07-01
    • 2018-01-07
    • 1970-01-01
    • 2012-02-20
    • 2015-07-05
    • 2016-11-12
    相关资源
    最近更新 更多