我知道在 stackoverflow 上已经有很多关于此的问题,但没有一个适用于我的情况。
在我的routes.rb
Exer9::Application.routes.draw do
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
resources :users
end
end
end
exer9/app/controllers/api/v1/users_controller.rb
module Api
module v1
class UsersController < ApplicationController
# GET /user
# GET /user.json
def index
@users = User.all
render json: @users
end
def new
end
def update
end
# GET /user/1
# GET /user/1.json
def show
@user = User.find(params[:id])
render json: @user
end
def create
@user = User.new(params[:user])
if @user.save
render json: @user
else
render json: @user.errors
end
end
def delete
end
def destroy
end
end
end
end
更新
这是我的ApplicationController文件
class ApplicationController < ActionController::API
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
# protect_from_forgery with: :exception
end
我得到的错误信息是:
superclass mismatch for class UsersController
Extracted source (around line #2):
1
2
3
4
5
6
class Api::V1::UsersController < ApplicationController
# GET /user
# GET /user.json
def index
Rails.root: /home/steven/Desktop/weekly-exercises/exer9
Application Trace | Framework Trace | Full Trace
app/controllers/api/v1/users_controller.rb:2:in `<top (required)>
'
非常感谢这里的任何帮助!
最佳答案
使用更短的语法,例如:
class Api::V1::UsersController < ApplicationController
# your code goes here
end
另外,重命名类和文件后是否重启 rails server?
关于ruby-on-rails - 未初始化的常量 API::V1::UserController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26797577/