使用命名空间和引用模型(从其他(mongoid/rails)继承)的正确方法是什么? [英] What is the proper way to use namespaces and reference models inheriting from other (mongoid/rails)?
问题描述
我有一个从Scenario
继承的模型HandlingScenario
.像这样:
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
但是当我尝试访问HandlingScenario
类时,我遇到了麻烦:
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:
控制器动作为:
## 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
推荐答案
将class_name选项用于关系"has_many:handling_scenarios",以便Rails知道模型handling_scenario位于文件场景/handling_scenario.rb中:
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
请参阅: http://mongoid.org/en/mongoid/docs/relations. html
此外,您无需在Scenarios :: HandlingScenario中包含Mongoid :: Document,因为它是从Scenario继承而来的.
Besides you dont need to include Mongoid::Document in your Scenarios::HandlingScenario since it is inherited from Scenario.
这篇关于使用命名空间和引用模型(从其他(mongoid/rails)继承)的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!