What is the proper way to use namespaces and reference models inheriting from other (mongoid/rails)?

StackOverflow https://stackoverflow.com/questions/19211962

Question

I have the model HandlingScenario who inherits from Scenario. Like this:

## models/scenario.rb
class Scenario
  include Mongoid::Document
end

## models/scenarios/handling_scenario.rb
class Scenarios::HandlingScenario < Scenario
  include Mongoid::Document
  belongs_to :user, :inverse_of => :handling_scenarios  # In the `User` model, the reference is `has_many :handling_scenarios`
end

But when I try to access the HandlingScenario class, I get into trouble:

➜  rails c
Loading development environment (Rails 3.2.12)
2.0.0-p247 :001 > User.first.handling_scenarios
LoadError: Expected /Users/christoffer/Projects/my_project/app/models/scenarios/handling_scenario.rb to define HandlingScenario

Also, when I try to visit through the browser I get this error:

Started GET "/scenarios/handling_scenarios" for 127.0.0.1 at 2013-10-06 19:41:29 +0200
Processing by Scenarios::HandlingScenariosController#index as HTML
  MOPED: 127.0.0.1:27017 QUERY        database=my_project_development collection=users selector={"$query"=>{"_id"=>"518f599683c336fb87000003"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (0.3998ms)
Completed 500 Internal Server Error in 7ms

NameError - uninitialized constant HandlingScenario:

The controller action is:

## controllers/scenarios/handling_scenarios_controller.rb
class Scenarios::HandlingScenariosController < ScenariosController
  def index
    @handling_scenarios = current_user.handling_scenarios
  end
end

And my routes are:

## config/routes.rb
namespace :scenarios do
  resources :handling_scenarios do
    member do
      ...
    end
  end
end
Was it helpful?

Solution

Use the class_name option for the relation 'has_many :handling_scenarios' so rails knows that the model handling_scenario is in the file scenarios/handling_scenario.rb:

## models/user.rb
class User
   include Mongoid::Document
   has_many :handling_scenarios, class_name: "Scenarios::HandlingScenario"
end

See: http://mongoid.org/en/mongoid/docs/relations.html

Besides you dont need to include Mongoid::Document in your Scenarios::HandlingScenario since it is inherited from Scenario.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top