2014-02-20 5 views
0

Я хотел бы подтвердить, что при сохранении моего события был введен хотя бы один параметр. Опция представляет собой встроенный документ с мангоидом. Как я могу это сделать?Проверить наличие встроенного документа?

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 вернуться ложным и не сохранить модель.

+0

thx попробует! ура – Mike

Смежные вопросы