0

我正在尝试对类似于 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

我有一些问题:

  1. 我怎样才能让两件事与一个模型有关系?一个问题可以有很多答案,而一个用户可以有很多答案。
  2. 如果我创建一个答案,question.answers.create()我如何将用户与之关联?我可以user_id手动设置或类似的东西吗?
4

1 回答 1

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
)
于 2013-06-06T04:04:37.000 回答