我已经看到1:N的这类问题的解决方案,但他们似乎没有读到1:1,这是使用MongoDB 1.8,Mongoid 2.0.0.rc.8,Rails 3.0.5
class Coach
include Mongoid::Document
field :name, :type => String
belongs_to :coached, :class_name => Team, :inverse_of => :coach, :foreign_key => "coach_id"
belongs_to :assisted, :class_name => Team, :inverse_of => :assist, :foreign_key => "assist_id"
end
class Team
include Mongoid::Document
field :name, :type => String
has_one :coach, :class_name => Coach, :inverse_of => :coached
has_one :assist, :class_name => Coach, :inverse_of => :assisted
end
然后我开始和Rails控制台会话和:
irb(main):001:0> c = Coach.new(:name => "Tom")
=> #<Coach _id: da18348d298ca47ad000001, _type: nil, _id: BSON::ObjectId('4da18348d298ca47ad000001'), name: "Tom", coach_id: nil, assist_id: nil>
irb(main):002:0> a = Coach.new(:name => "Dick")
=> #<Coach _id: 4da18352d298ca47ad000002, _type: nil, _id: BSON::ObjectId('4da18352d298ca47ad000002'), name: "Dick", coach_id: nil, assist_id: nil>
irb(main):003:0> t = Team.new(:name => "Allstars")
=> #<Team _id: 4da18362d298ca47ad000003, _type: nil, _id: BSON::ObjectId('4da18362d298ca47ad000003'), name: "Allstars">
irb(main):005:0> t.coach = c
NoMethodError: undefined method `constantize' for Coach:Class
irb(main):005:0> c.coached = t
NoMethodError: undefined method `constantize' for Team:Class
任何建议将不胜感激!
答案 0 :(得分:8)
您在定义Team
时引用了类Coach
,但该类尚不存在。
您有两种选择:
class_name
声明为字符串而不是常量,例如:class_name => 'Team'
(首选,请参阅gist):class_name => Team
选项,让Mongoid找出参与关联的正确类。 有一点需要注意:您需要确保在类Team
之前声明类Coach
(加载源代码的顺序现在很重要,因此此解决方案并不理想)