Warwick Hall
Warwick Hall

Reputation: 209

Ruby on Rails route to controller not working

Attempting to create an API using doorkeeper. When I sign into my account and the session user is authenticated and access my API on

http://localhost:3000/api/v1/trials

I get a routing error page saying "uninitialized constant TrialsController" and a rake routes listing. Including:

trials_path    GET    /api/v1/trials(.:format)    trials#index

I am using rails version 4.0.3, ruby 2.0.0. This is my config/routes.rb file:

MyApp::Application.routes.draw do
  devise_for :users

  use_doorkeeper :scope => 'oauth2' do
  end

  root :to => 'welcome#index'
  scope 'api' do
    scope 'v1' do
      resources :trials
    end
  end
end

My app/ dir contains:

app/
    controllers/
        application_controller.rb
        welcome_controller.rb
        api/
           v1/
               trials_controller.rb

My trials_controller.rb is:

module Api::V1
  class TrialsController < ::ApplicationController
    doorkeeper_for :all

    def index
      @trials = Trials.all
    end

    def show
      ...
    end

    ...

  end
end

UPDATE: When I change the routes.rb to namespace the trails controller like so:

  namespace :api do
    namespace :v1 do
      resources :trails
    end
  end

I get a "no route matches" error when attempting to access:

http://localhost:3000/api/v1/trials(.json)

(With or without the extension.)

I have also added to trials#index:

    def index
      @trials = Trials.all
      respond_to do |format|
        format.json { render :json => @trials }
        format.xml { render :xml => @trials }
      end
    end

Also with no luck.

Upvotes: 0

Views: 1215

Answers (1)

craig.kaminsky
craig.kaminsky

Reputation: 5598

I'm not sure how it would play out against doorkeeper but I have a similar API structure in an app. I have the following in my routes (matching what Sergio notes)

namespace :api, defaults: {format: 'json'} do
  namespace :v1 do
    resources :api_controller_1
    resources :api_controller_2
  end
end

And here's how I build my API classes:

module Api
  module V1
    class ApiNamedController < ApplicationController
      # code
    end
  end
end

Upvotes: 1

Related Questions