【问题标题】:Rails-Api (4): Namespaced routes, only: actionsRails-Api (4):命名空间路由,仅:动作
【发布时间】:2014-11-03 20:57:24
【问题描述】:

我正在使用 Rails-Api (4),我只需要三个路由用于我的命名空间路由文件。

在我的 routes.rb 文件中,我正在尝试这样做:

namespace :api do
  namespace :v1 do
    resources :documents, only: [:get, :create]
    resource :system_status, only: [:get]        
  end
end

rake routes 只给我这个:

          Prefix Verb URI Pattern                 Controller#Action
api_v1_documents POST /api/v1/documents(.:format) api/v1/documents#create

如果关闭only:,它会起作用并为我提供所有路线(我不想要)。

我也试过这个:

namespace :api do
  namespace :v1 do
    post '/documents',     to: 'documents#create'
    get  '/documents/:id', to: 'documents#show'
    get  '/system_status', to: 'system_status#show'    
  end
end

rake routes 中得到这个奇怪的输出:

              Prefix Verb URI Pattern                     Controller#Action
    api_v1_documents POST /api/v1/documents(.:format)     api/v1/documents#create
              api_v1 GET  /api/v1/documents/:id(.:format) api/v1/documents#show
api_v1_system_status GET  /api/v1/system_status(.:format) api/v1/system_status#show

不确定documents#show 的前缀是api_v1 是怎么回事。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rails-routing rails-api


    【解决方案1】:

    看起来你在 HTTP 动词和它们对应的 Rails 动作之间搞混了。 :get没有资源路由,但是GET请求有两条路由,分别是:index:show

    改为将原来的基于资源的路由改为:

    namespace :api do
      namespace :v1 do
        resources :documents, only: [:show, :create]
        resource :system_status, only: [:show]        
      end
    end
    

    这应该会为您提供正确的路由,以及正确的 URL 帮助器前缀。

    【讨论】:

    • @MichaelH。发生在我们最好的人身上。祝你好运! (另外,请不要忘记接受答案)
    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多