I am quite new to mongoDB and I’m just using it for a new rails project I’m working on.
What I wanted to do now is, having an (embedded) document reference another collection, but with different roles.
Somehow this doesn’t seem to work. I know, that I can’t define a relation from an external collection to my embedded one. So in my case, I cannot acces the Locations from my User and I’m fine with that. Still, I need to define the referenced_in :location part, because otherwise I get an error message undefined method 'name' for nil:NilClass when I try to add a new Location to the Place.
So that’s just the preface. My actual problem is, that these roles thing doesn’t seem to work. When I create a new Location like that in a Place locations.create(:user_a => some_user), then also user_b is set to that user.
Is there any way to make this working? Or am I doing something wrong?
class Place
include Mongoid::Document
embeds_many :locations
end
class Location
include Mongoid::Document
embedded_in :place, :inverse_of => :locations
references_one :user_a, :class_name => "User" #, :stored_as => :array
references_one :user_b, :class_name => "User" #, :stored_as => :array
end
class User
include Mongoid::Document
referenced_in :location, :inverse_of => :dropper
referenced_in :location, :inverse_of => :picker
end
I think you have to disambiguate the two location associations (because the reference is stored on the referenced_in side):
I can’t help feeling that there may be a better way to do this though…
Is this a better approach?