Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...