我想确认在保存活动时至少输入了一个选项。选项是嵌入式mongoid文档。我怎么能这样做?
class Event
include Mongoid::Document
field :name, type: String
field :description, type: String
field :date, type: Date
embeds_many :invitees, cascade_callbacks: true
embeds_many :participants, cascade_callbacks: true
embeds_many :comments, cascade_callbacks: true
embeds_many :options, cascade_callbacks: true
has_one :owner, :class_name => "User"
validates :name, :date, :presence => true
accepts_nested_attributes_for :options, autosave: true, allow_destroy: true
accepts_nested_attributes_for :participants, autosave: true, allow_destroy: true
accepts_nested_attributes_for :comments, autosave: true, allow_destroy: true
accepts_nested_attributes_for :invitees, autosave: true, allow_destroy: true
accepts_nested_attributes_for :owner, autosave: true, allow_destroy: true
end
答案 0 :(得分:2)
您可以使用自定义验证程序执行此操作。
validate :has_at_least_one_option
def has_at_least_one_option
if options.empty?
errors[:base] << "Please choose at least one option"
end
end
出现错误将导致对save
的调用返回false并且无法保存模型。