2014-02-20 42 views
0

我想验证在保存我的活动时至少输入了一个选项。 Option是一个嵌入式的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 

回答

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并不能保存模型。

+0

thx会试用它!干杯 – Mike