如何在嵌套模型中验证附件?

时间:2013-03-19 05:26:56

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

我有一个设计模型,在两个关联(full_image和preview)中有两个Paperclip附件。我希望只有当full_image和preview都有有效文件但似乎无法使其工作时才能保存设计。现在这是我期望的工作,但是当我提交表单时,它不仅不会验证附件。

class Design < ActiveRecord::Base

  has_one :full_image, :as => :assetable, :class_name => "FullImage", :dependent => :destroy
  has_one :preview   , :as => :assetable, :class_name => "Preview"  , :dependent => :destroy

  accepts_nested_attributes_for :full_image, :preview
  validates_associated :preview, :full_image

end

class Asset < ActiveRecord::Base
    belongs_to :assetable, :polymorphic => true
    delegate :url, :to => :attachment
end

class FullImage < Asset
    has_attached_file :attachment
    validates_attachment_presence :attachment
end

class Preview < Asset
    has_attached_file :attachment
    validates_attachment_presence :attachment
end

有人可以建议我应该做些什么吗?

2 个答案:

答案 0 :(得分:1)

尝试: 验证:附件,:presence =&gt;真正 在关联模型中而不是validates_attachment_presence

答案 1 :(得分:0)

以下是我如何运作

class Design < ActiveRecord::Base

  has_one :full_image, :as => :assetable, :class_name => "FullImage", :dependent => :destroy
  has_one :preview   , :as => :assetable, :class_name => "Preview"  , :dependent => :destroy

  accepts_nested_attributes_for :full_image, :preview

  validates_presence_of :preview
  validates_presence_of :full_image

end

class Asset < ActiveRecord::Base
    belongs_to :assetable, :polymorphic => true
    delegate :url, :to => :attachment
end

class FullImage < Asset
    has_attached_file :attachment
end

class Preview < Asset
    has_attached_file :attachment
end