4
我已經看到了1:N這類問題的解決方案,但它們看起來並沒有讀到1:1,這是使用MongoDB 1.8,Mongoid 2.0.0.rc.8來說,Rails 3.0.5Mongoid使用has_one將一個對象與同一類的兩個不同對象相關聯
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
任何建議,將不勝感激!
良好,即不它非常感謝 – Indigo 2011-04-17 09:50:57
+1以上的答案,如果有人看到錯誤,它抱怨NoMethodError,那麼它很可能與加載問題有關。將class_name聲明爲字符串可以解決問題。 – 2013-10-31 19:10:00