【发布时间】:2020-01-14 18:03:25
【问题描述】:
为我的第一个 Rails 项目做 API。 我有所有 API 的基类 ApiController:
module Api
class ApiController < ::ApplicationController
respond_to :json
skip_before_action :verify_authenticity_token
def index
@collection = resource_class.all
render json: @collection.as_json(as_json_collection)
end
private
def resource_class
raise NotImplementedError
end
def as_json_collection
{}
end
end
end
我有子类UsersController:
module Api
class UsersController < ApiController
private
def resource_class
User
end
def resource_params
params.require(:user).permit(:name, :email)
end
end
end
我的路线:
namespace :api do
resources :users
end
那我去 my_app/api/users 我有错误:
找不到 Api::UsersController 的操作“索引”
但后来我更改了 UsersController 编写它自己的索引类,一切正常,我的所有用户都采用 JSON 格式。 我已经尝试评论两个课程中的所有私人标记,但这无济于事。 我不想为我的项目中的每个实体编写一个 API,我希望以后避免这个问题。
【问题讨论】:
标签: ruby-on-rails