1

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 ルートは返しません。

4

2 に答える 2

2

fromもjsonapi_resources派生させる必要があるため、が機能しない最も可能性の高い理由は次のとおりです。Application ControllerJSONAPI::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

もう 1 つのことは (これはルートが消える原因ではありません)、ルートでリソースの複数形を使用することです。以下のように使用goalsします NOT goal:

Rails.application.routes.draw do
  # other routes here

  namespace :api, defaults: { format: 'json' } do
    jsonapi_resources :goals
  end
end

を使ったデモアプリですjsonapi_resources

于 2015-08-22T17:24:05.333 に答える
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はまだ完全に機能します!

于 2015-08-23T08:25:31.927 に答える