Mongoid binding one object to two different objects of the same class using has_one

I see solutions to this problem with 1: N, but they don't seem to read up to 1: 1, this uses 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 

Then I start a Rails console session and:

 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 

Any advice would be greatly appreciated!

+4
source share
1 answer

You specify the Team class when defining Coach , but the class does not yet exist. You have two options:

  • Declare class_name as a string instead of a constant, for example. :class_name => 'Team' (preferred, see gist )
  • Completely remove the option :class_name => Team , and let Mongoid determine the correct classes involved in the association. There is one caveat:. You will need to make sure that the Team class is declared before the Coach class (now the source code loading order is required, so this solution is not ideal)
+8
source

Source: https://habr.com/ru/post/1347838/


All Articles