내 첫 번째 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에 대한 'index'작업을 찾을 수 없습니다.
하지만 그런 다음 자체 인덱스 클래스를 작성하는 UsersController를 변경하면 모든 것이 잘 작동하며 모든 사용자가 JSON 형식으로 표시됩니다. 나는 alrady가 두 클래스의 모든 개인 표시에 대해 주석을 달려고 노력했지만 도움이되지 않습니다. 내 프로젝트의 모든 엔터티에 대해 API를 작성하고 싶지 않으며 앞으로이 문제를 피하고 싶습니다.
이 작업을 수행했습니다.
module Api
class ApiController < ::ApplicationController
def index
respond_to do |format|
format.json { render json: '"abc"' }
end
end
end
end
module Api
class UsersController < ApiController
end
end
URL은 http://localhost:3000/api/users.json
그래서 당신을 위해 제안합니다.
module Api
class ApiController < ::ApplicationController
def index
respond_to do |format|
format.json do
@collection = resource_class.all
render json: @collection.as_json(as_json_collection)
end
end
end
end
end
module Api
class UsersController < ApiController
def resource_class
User
end
def resource_params
params.require(:user).permit(:name, :email)
end
end
end
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다