Reputation: 5283
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
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
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