使用从其他(mongoid / rails)继承的名称空间和引用模型的正确方法是什么?

时间:2013-10-06 17:53:54

标签: ruby-on-rails mongoid rails-models

我的模型HandlingScenario继承自Scenario。像这样:

## 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

但是当我尝试访问HandlingScenario课程时,我遇到了麻烦:

➜  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

此外,当我尝试通过浏览器访问时,我收到此错误:

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:

控制器操作是:

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

我的路线是:

## config/routes.rb
namespace :scenarios do
  resources :handling_scenarios do
    member do
      ...
    end
  end
end

1 个答案:

答案 0 :(得分:3)

对关系'has_many:handling_scenarios'使用class_name选项,因此rails知道模型handling_scenario位于文件scenario / handling_scenario.rb中:

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

请参阅:http://mongoid.org/en/mongoid/docs/relations.html

此外,您不需要在Scenarios :: HandlingScenario中包含Mongoid :: Document,因为它是从Scenario继承的。