pjb3
pjb3

Reputation: 5283

How do you make a belongs_to required with mongo mapper?

I am using Mongo Mapper and I'm trying to figure out how you make a document required. For example, I want to do something like this:

class Question
  include MongoMapper::Document

  many :answers
end

class Answer
  include MongoMapper::Document

  belongs_to :question, :required => true
end

But when I do, it's doesn't enforce that the answer have a question:

> Answer.new.save
 => true

Upvotes: 1

Views: 451

Answers (2)

Mario Visic
Mario Visic

Reputation: 2663

MongoMapper includes ActiveModel::Validations so you can use validations just like active record. The following should work:

class Question
  include MongoMapper::Document

  many :answers
end

class Answer
  include MongoMapper::Document

  belongs_to :question

  validates :question, :presence => true
end

You can check the rails docs for more info on those validations here: http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates

Upvotes: 4

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

What about some callbacks?

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

Upvotes: 0

Related Questions