我正在尝试使用JSONAPI Resource gem为我的rails应用程序创建API。我希望能够利用我的控制器利用普通的rails路由,并且还有一个命名空间的API。
到目前为止,我有类似
的内容# sitting in resources/api/goal_resource.rb
module Api
class GoalResource < JSONAPI::Resource
attributes :name, :description, :progress
end
end
Rails.application.routes.draw do
devise_for :users,
path: '',
controllers: {
registrations: 'users/registrations',
invitations: 'users/invitations',
sessions: 'users/sessions'
},
path_names: {
edit: 'settings/profile'
}
devise_scope :user do
authenticated :user do
root 'dashboard#index', as: :authenticated_root
end
unauthenticated do
root 'users/sessions#new', as: :unauthenticated_root
end
end
post '/invitation/:id/resend', to: 'users/invitations#resend', as: :resend_invitation
resources :goals do
resources :goal_comments
resources :goal_followers, only: [:index]
member do
post :on_target, as: :on_target
end
end
resources :users, path: '/settings/users', only: [:index, :update, :edit, :destroy]
resources :teams, path: '/settings/teams', only: [:index, :new, :create, :update, :edit, :destroy]
resources :notifications, only: [:index]
get "my_goals", to: "my_goals#index", as: :my_goals
get "user_goals/:user_id", to: "user_goals#index", as: :user_goals
get "team_goals/:team_id", to: "team_goals#index", as: :team_goals
namespace :api, defaults: { format: 'json' } do
jsonapi_resources :goals
end
end
# Gemfile
source 'https://rubygems.org'
ruby '2.1.2'
gem 'jsonapi-resources'
# other gems here
# models/goal.rb
class Goal < ActiveRecord::Base
# some more code here
end
是否可以将此gem与正常路由结合使用?我究竟做错了什么? rake routes
返回我的应用程序的所有路由,但没有api路由。
答案 0 :(得分:2)
Format = (FORMAT) GetProcAddress(hModule, "doParseFormat");
无效的最可能原因是您必须从jsonapi_resources
派生Application Controller
:
JSONAPI::ResourceController
另一件事是(这不会导致你的路线消失),使用路线中的复数资源。使用class ApplicationController < JSONAPI::ResourceController
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session
end
,如下面的goals
:
goal
以下是使用Rails.application.routes.draw do
# other routes here
namespace :api, defaults: { format: 'json' } do
jsonapi_resources :goals
end
end
的{{3}}。
答案 1 :(得分:0)
我设法让它发挥作用
# app/controllers/api/api_controller.rb
module Api
class ApiController < JSONAPI::ResourceController
end
end
# app/controllers/api/goals_controller.rb
module Api
class GoalsController < ApiController
end
end
我刚刚创建了一个单独的ApiController
并继承了JSONAPI::ResourceController
,然后我为我的目标创建了一个额外的控制器。
我的正常controllers/goals_controller.rb
仍能完美运作!