2014-11-25 133 views
0

我试图创建简单的Ruby on Rails REST API。Ruby on Rails生根错误

应用程序/控制器/ API/VI/product_controller.rb

module Api 
    module V1 
     class ProductController < ApplicationController::API 
      def index 
       render json: {message: 'Welcome!'} 
      end 
     end 
    end 
end 

的config/routes.rb中

Rails.application.routes.draw do 
    namespace :api do 
    namespace :v1 do 
     get '/product', to: 'product_controller#index', as: 'product' 
    end 
    end 
end 

当我运行在本地主机上的项目,我得到uninitialized constant Api::V1::ApplicationController路由错误。任何人都可以帮助像这样的Ruby on Rails新手,因为我是?

+0

改变这一行,并尝试一次:'类ProductController的 Choco 2014-11-25 08:55:32

+0

错误: '未初始化的常量ApiController' – 2014-11-25 08:57:43

+0

'ApplicationController :: API'从哪里来? – 2014-11-25 09:08:37

回答

0

您嵌套的路线,所以它应该是“/ API/V1/product`

如果您从控制台运行rake routes,你会得到所有可用路由的列表。

有关路由和嵌套路由的详细信息,看看rails guides

+0

'get'/ product',to:'product#index',as:'product''?这个行代码仍然是一样的错误... – 2014-11-25 08:15:11

+0

'rake routes'输出:'api_v1_product GET /api/v1/product(.:format)api/v1/product#index' – 2014-11-25 08:17:01

0

改变这一点,并尝试:

module Api 
    module V1 
     class ProductController < ApplicationController 
      def index 
       render json: {message: 'Welcome!'} 
      end 
     end 
    end 
end 
+0

'未初始化的常量Api :: V1: :ApiController' – 2014-11-25 09:23:54

+0

@JacobJones我编辑我的答案,请检查它 – Choco 2014-11-25 09:29:10

+0

'未初始化的常量ApplicationController' – 2014-11-25 09:32:25

1

你只需要创建一个内部控制器调用的API文件夹,里面V1文件夹API。 您应该提供v1文件夹内的所有控制器。

在您的应用程序/控制器/ API/V1/product_controller.rb

class Api::V1::ProductController < ApplicationController 
    def index 
     render json: {message: 'Welcome!'} 
    end 
end 

在你的路线:

Rails.application.routes.draw do 
    namespace :api do 
    namespace :v1 do 
     get '/product', to: 'product_controller#index', as: 'product' 
    end 
    end 
end