Reputation: 1152
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?
Upvotes: 1
Views: 246
Reputation: 14490
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.
Upvotes: 2