【问题标题】:Validating embedded document in Mongoid在 Mongoid 中验证嵌入文档
【发布时间】:2012-09-06 01:39:23
【问题描述】:

我有一个文档 Design.rb,它有一个嵌入式文档 Attachment.rb,它进行了一些验证。如果 Attachment.rb 失败,那么 Design.rb 也应该失败,但它不会。

如果嵌入式文档失败,我如何让我的设计类失败,有什么建议吗?

设计.rb:

class Design

    embeds_many :attachments, :as => :attachable

    validates_associated :attachments

    accepts_nested_attributes_for :attachments, :allow_destroy => true

    field :description
    field :title
    field :tags, type: Array
    field :featured, :type => Boolean, :default => false
    field :full_member, :type => Boolean, :default => false
    field :first_design, :type => Boolean, :default => false
    field :option, :type => String 
    field :app_store_url, :type => String 
    field :design_in_progress, :type => Boolean

    attr_accessible :design_in_progress, :tags, :description, :title, :featured, :project_number, :show, :option, :app_store_url, :temp_number, :option, :attachments_attributes

    validates :description, :tags, :title, :presence => true

end

附件.rb

require 'carrierwave/mongoid'

class Attachment

    embedded_in :attachable, :polymorphic => true, :inverse_of => :attachments

    field :image
    field :width, :type => Integer
    field :height, :type => Integer
    field :option, :type => String

    attr_accessible :image, :width, :height, :option, :normal, :url

    mount_uploader :image, ImageUploader

    validate :validate_minimum_image_size

    def validate_minimum_image_size
        self.option = self.attachable.option

        case self.option
        when "iphone"
            width = 640
            height = 960
            type = "iPhone"
        when "ipad"
            width = 1536
            height = 2048
            type = "iPad"
        when "icon"
            width = 1024
            height = 1024
            type = "Icon"
        when "wp" 
            width = 480
            height = 800
            type = "Windows Phone"
        when "android"
            width = 480
            height = 800
            type = "Android"
        end

        geometry = self.image.geometry
        unless geometry.nil?
            self.width = geometry[0]
            self.height = geometry[1]
        end

        unless (self.width == width && self.height == height)
            puts "INSIDE ERROR STATEMENT" 
            errors.add :base, "Naughty you... "+type+" designs should be "+width.to_s+"px times "+height.to_s+"px. We want to see your awesome design in retina :-)." 
        end
    end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid


    【解决方案1】:

    你可以试试添加

    embeds_many :attachments, :as => :attachable, cascade_callbacks: true
    

    当通过设计模型进行更改时将调用验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 2011-04-11
      相关资源
      最近更新 更多