2

我有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
4

1 回答 1

3

对关系 'has_many :handling_scenario' 使用 class_name 选项,因此 rails 知道模型 handling_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

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

于 2013-10-07T08:53:26.977 回答