Luigi
Luigi

Reputation: 5603

Uninitialized Constant in Rails Controller

I have the following in my controller:

class SurveysController < ApplicationController

  def index
    survey_provider = FluidSurveysProviders::SurveyProvider.new
    contact_lists = survey_provider.get_lists()
    @survey = Survey.new(contact_lists)
  end

And I'm receiving this error:

NameError in SurveysController#index
uninitialized constant SurveysController::FluidSurveysProviders

Excuse my Rails noobiness, I'm sure I'm leaving out something important here. But it seems to me that I am trying to "initialize" the constant with this line:

survey_provider = FluidSurveysProviders::SurveyProvider.new

But that's the same line that's throwing an error because it's not initialized. Where should I be "initializing" the Provider?

Upvotes: 1

Views: 2552

Answers (3)

Trang Tung Nguyen
Trang Tung Nguyen

Reputation: 346

The SurveyProvider was not loaded correctly.

  1. For a quick fix, move the class file into app directory, e.g. app/lib/survey_provider.rb. Then all code inside app will be auto-loaded by Rails.
  2. Or make sure the path to class SurveyProvider is included in the autoload_path of Rails. In config/application.rb

    config.autoload_paths += %W(#{config.root}/lib) # where lib is directory to survery_provider

    If you use Rails 5, be careful that autoload is disabled in production environment. Check this link for more info.

Upvotes: 0

Timbinous
Timbinous

Reputation: 2983

Make sure SurveyProvider is wrapped with module FluidSurveysProviders. It may look like this

module FluidSurveysProviders
  class SurveyProvider
    ...
  end
end

if its an ActiveRecord object try this

class FluidSurveysProviders::SurveyProvider < ActiveRecord::Base
  ...
end

Upvotes: 0

Vidya
Vidya

Reputation: 30310

Once you require fluid_surveys_providers (or similar) then do this:

include FluidSurveysProviders

Upvotes: 1

Related Questions