Tom Hammond
Tom Hammond

Reputation: 6080

Rails API Issue

I'm on Mac OS Mavericks and using Ruby 2.0.0p353.

While following the "#350 REST API Versioning" railscast to create a restful API on my website, I encountered this error:

RuntimeError in Api::V1::SurveysController#index
Circular dependency detected while autoloading constant Api::V1::SurveysController

Rails.root: /Users/thomashammond89/SurveyMe
Application Trace | Framework Trace | Full Trace

Request

Parameters:

{"format"=>"json"}

Here's my surveys_controller, found under controllers/api/v1:

module Api
  module V1
    class ProductsController < ApplicationController
      before_filter :restrict_access
      respond_to :json

      def index
        respond_with Survey.all
      end

      def show
        respond_with Survey.find(params[:id])
      end

      def create
        respond_with Survey.create(params[:survey])
      end

      def update
        respond_with Survey.update(params[:id], params[:survey])
      end

      def destroy
        respond_with Survey.destroy(params[:id])
      end

      def restrict_access
        api_key = ApiKey.find_by_access_token(params[:access_token])
        head :unauthorized unless api_key
      end
    end
  end
end

The api_key model:

class ApiKey < ActiveRecord::Base
  before_create :generate_access_token

  private

  def generate_access_token
    self.access_token = SecureRandom.hex
  end while self.class.exists?(access_token: access_token)

end

And my routes:

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

Any idea what I'm doing wrong or where that error is coming from? I tried changing my Rails version from 4.0.1 to 4.0.0 following "Circular dependency detected while autoloading constant".

"Circular dependency detected while autoloading constant User" alludes to the issue being that he has two of the same controllers, one under the api folder. I also have two surveys_controllers.rb. Could this be causing the issue? If so, does someone know how I should set-up the controller under the api folder so that my surveys display? The railscast has me create a second controller.

Upvotes: 0

Views: 189

Answers (1)

Matt
Matt

Reputation: 20766

The generate_access_token function should be

def generate_access_token
  begin
    self.access_token = SecureRandom.hex
  end while self.class.exists?(access_token: access_token)
end

Upvotes: 2

Related Questions