Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

mongodb - Accessing embedded document parent in rails engine mongoid

I am in the process of converting some code that previously worked with no issues into a rails namespaced engine so it can be reused. Here is an example that is not currently working for me:

module MyModule
  class School
    include Mongoid::Document
    
    embeds_one :student

  end
end

module MyModule
  class Student
    include Mongoid::Document
    
    embedded_in :school

  end
end

However, when I create a school and assign it a student and try to access its parent via the school property, it returns nil.

school = MyModule::School.create
school.student = MyModule::Student.new
school.save!

school.student.school // return nil
school.student._parent // returns the school object

What am I doing wrong that is causing school.student.school to return nil?

question from:https://stackoverflow.com/questions/65646225/accessing-embedded-document-parent-in-rails-engine-mongoid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are missing the class names on associations:

module MyModule
  class School
    include Mongoid::Document
    
    embeds_one :student, class_name: 'MyModule::Student'

  end
end

module MyModule
  class Student
    include Mongoid::Document
    
    embedded_in :school, class_name: 'MyModule::School'

  end
end

An argument can be made that Mongoid should figure this out automatically, though a complication here is when the first of the models is loaded the other one isn't defined yet and hence the target class may be global or in the namespace and Mongoid has no way of knowing which is correct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...