Reputation: 223
I have two collections in my DB-
> db.users.find().pretty()
{
"_id" : ObjectId("5281c15a617274166f150000"),
"email" : "[email protected]",
"nickname" : "Artem",
"user_activities" : [
{
"_id" : ObjectId("5281c19161727415d5000000"),
"activity_id" : ObjectId("5281c15a617274166f010000"),
...
},
{
"_id" : ObjectId("5281c19161727415d6000000"),
"activity_id" : ObjectId("5281c15a617274166f020000"),
...
},
...
]
},
....
and
> db.monitor_symptoms.find().pretty()
{
"_id" : ObjectId("5281c15a617274166f000000"),
"activities" : [
{
"_id" : ObjectId("5281c15a617274166f010000"),
"name" : "ASW"
...
},
{
"_id" : ObjectId("5281c15a617274166f010000"),
"name" : "BSW"
...
},
...
],
...
},
...
This is supported by the following models in my app-
class User
include Mongoid::Document
field :email, type: String, :default => ""
field :nickname, type: String, :default => ""
embeds_many :user_activities
end
class UserActivity
include Mongoid::Document
embedded_in :user
has_to_many :activities, inverse_of: nil
end
class MonitorSymptom
include Mongoid::Document
embeds_many :activities
end
class Activity
include Mongoid::Document
field :name, type: String
embedded_in :monitor_symptom
end
I try next-
2.0.0p0 :090 > user = User.first
=> #<User _id: 5281c15a617274166f150000, email: "[email protected]", nickname: "Artem"
2.0.0p0 :091 > user.user_activities.new(activity_id: "5281c15a617274166f010000")
=> #<UserActivity _id: 5281c15a617274166f150000, activity_id: "5281c15a617274166f010000">
2.0.0p0 :092 > user.save
And I catch an error:
Mongoid::Errors::MixedRelations: Problem: Referencing a(n) Activity document from the UserActivity document via a relational association is not allowed since the Activity is embedded. Summary: In order to properly access a(n) Activity from UserActivity the reference would need to go through the root document of Activity. In a simple case this would require Mongoid to store an extra foreign key for the root, in more complex cases where Activity is multiple levels deep a key would need to be stored for each parent up the hierarchy. Resolution: Consider not embedding Activity, or do the key storage and access in a custom manner in the application code.
Please help me to make this reference.
Upvotes: 1
Views: 314
Reputation: 5213
The model which is embedded_in some other model can't have relationships other than embed...for your case activity
is embedded in monitor_symptom
it can't be refrenced from other document(hich you are doing in user_activity
). When you have such a complex structure, it is better to use refrenced relationship between document rather than embed. For e.g. in between user and user_activity, monitor_symptom and activity then you can easily have refrenced relationship between activity and user_activity.
Upvotes: 2