我正在尝试建模类似于StackOverflow的问题/答案系统,因为有一个问题,它有答案,问题和答案都属于不同的用户(但答案也属于问题)我的代码如下:
class User
include MongoMapper::Document
many :questions
timestamps!
end
class Question
include MongoMapper::Document
belongs_to :user
many :answers
many :comments
timestamps!
end
class Answer
include MongoMapper::Document
belongs_to :question
many :comments
timestamps!
end
我有几个问题:
question.answers.create()
创建答案,如何将用户与其关联?我可以手动设置user_id
或类似的东西吗?答案 0 :(得分:0)
我自己想通了 - 我不太明白是什么让我相信我不能只有多种关系。我多么封闭了!
对于其他被困的人:
class User
include MongoMapper::Document
many :questions
many :answers
timestamps!
end
class Question
include MongoMapper::Document
belongs_to :user
many :answers
many :comments
timestamps!
end
class Answer
include MongoMapper::Document
belongs_to :question
belongs_to :user
many :comments
timestamps!
end
像这样创建新的'答案':
q = Question.find(id)
u = User.find(id)
a = q.answers.create(
:user_id => u._id
)