你如何使用mongo mapper制作belongs_to?

时间:2011-12-24 14:38:12

标签: ruby mongodb mongomapper

我正在使用Mongo Mapper而我正在试图弄清楚如何制作文档。例如,我想做这样的事情:

class Question
  include MongoMapper::Document

  many :answers
end

class Answer
  include MongoMapper::Document

  belongs_to :question, :required => true
end

但是当我这样做时,并没有强制说答案有问题:

> Answer.new.save
 => true

2 个答案:

答案 0 :(得分:4)

MongoMapper包含ActiveModel :: Validations,因此您可以像活动记录一样使用验证。以下应该有效:

class Question
  include MongoMapper::Document

  many :answers
end

class Answer
  include MongoMapper::Document

  belongs_to :question

  validates :question, :presence => true
end

您可以在此处查看rails文档以获取有关这些验证的更多信息:http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates

答案 1 :(得分:0)

一些回调怎么办?

class Answer
  include MongoMapper::Document

  belongs_to :question

  def before_save
    # if question is nil, return false (this cancels save)
    return false unless question
    true
  end
end