【问题标题】:routing error, no route match for rails api request路由错误,rails api 请求没有路由匹配
【发布时间】:2019-12-15 20:43:55
【问题描述】:

我的控制器命名空间为 API,由于以下错误,我似乎无法发出请求: ActionController::RoutingError (No route matches [GET] "/api/request_projects")

控制器:

module Api
  class Api::ProjectsController < ApplicationController  
    def request_projects
      items = []
      page = 1
      total_count = Project.request_total_count
      pages = Project.get_page_count(total_count)
      pages.times do
        items << Project.request_projects(page)
        items_list = items.flatten
        Project.create_from_request(items_list) if !items_list.empty?
        page += 1
      end
    end
  end
end

路线:

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'pages#index'

  namespace :api, defaults: { format: 'json' } do
    resources :projects
  end

  match '*path', to: 'projects#request_projects', via: :all
end

【问题讨论】:

    标签: ruby-on-rails routes request initialization constants


    【解决方案1】:

    你声明Api::Api::ProjectsController

    module Api
      class ProjectsController < ApplicationController  
        def request_projects
          items = []
          page = 1
          total_count = Project.request_total_count
          pages = Project.get_page_count(total_count)
          pages.times do
            items << Project.request_projects(page)
            items_list = items.flatten
            Project.create_from_request(items_list) if !items_list.empty?
            page += 1
          end
        end
      end
    end
    

    使用显式定义(并重新打开)命名空间的类和模块 嵌套。使用范围解析运算符可能会导致令人惊讶的 由于 Ruby 的词法作用域,不断查找,这取决于 在定义点嵌套模块。
    - https://github.com/rubocop-hq/ruby-style-guide

    关于路由问题 - 您定义了一个包罗万象的定义,应该匹配 /api/request_projects。因为*path 将匹配所有内容。我不知道你为什么要这样做。只需声明您要使用的实际路线即可。 Catch-alls 是最后的手段,它会带来大量潜在的错误。

    Rails.application.routes.draw do
      # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
      root 'pages#index'
    
      namespace :api, defaults: { format: 'json' } do
        resources :projects
        resources :request_projects
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多