我的数据库中有两个集合-
> db.users.find().pretty()
{
"_id" : ObjectId("5281c15a617274166f150000"),
"email" : "aerf@gmail.com",
"nickname" : "Artem",
"user_activities" : [
{
"_id" : ObjectId("5281c19161727415d5000000"),
"activity_id" : ObjectId("5281c15a617274166f010000"),
...
},
{
"_id" : ObjectId("5281c19161727415d6000000"),
"activity_id" : ObjectId("5281c15a617274166f020000"),
...
},
...
]
},
....
和
> db.monitor_symptoms.find().pretty()
{
"_id" : ObjectId("5281c15a617274166f000000"),
"activities" : [
{
"_id" : ObjectId("5281c15a617274166f010000"),
"name" : "ASW"
...
},
{
"_id" : ObjectId("5281c15a617274166f010000"),
"name" : "BSW"
...
},
...
],
...
},
...
我的应用程序中的以下模型支持此功能-
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
接下来我试试——
2.0.0p0 :090 > user = User.first
=> #<User _id: 5281c15a617274166f150000, email: "aerf@gmail.com", 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
我发现一个错误:
Mongoid::Errors::MixedRelations: 问题:不允许通过关系关联从 UserActivity 文档引用 a(n) Activity 文档,因为 Activity 是嵌入的。摘要:为了从 UserActivity 正确访问一个(n)Activity,引用需要通过 Activity 的根文档。在一个简单的情况下,这将需要 Mongoid 为根存储一个额外的外键,在更复杂的情况下,如果 Activity 是多个级别的深度,则需要为层次结构中的每个父级存储一个键。解决方法:考虑不嵌入Activity,或者在应用代码中以自定义的方式进行key的存储和访问。
请帮我做这个参考。