MongoMapper在一个模型上有两个一对多的关系

时间:2013-06-06 03:59:15

标签: ruby activerecord sinatra mongomapper

我正在尝试建模类似于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或类似的东西吗?

1 个答案:

答案 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
)