0

我与带有配置文件和文档表的附件模型具有多态关联。我在 attachment.rb 中包含了以下代码:

class Attachment < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true
  has_attached_file :attach,
                    :storage => :s3,
                    :s3_credentials => "#{Rails.root}/config/s3.yml",
                    :url => ":s3_domain_url",
                    :path => "/contents/:id/:basename.:extension"
  validates_attachment_content_type :attach,
                                    :content_type => ['application/msword',
                                                       'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                                                       'application/pdf',
                                                       'image/jpeg', 'image/jpg', 'image/png']
end

在我的 profile.rb 中

class Profile < ActiveRecord::Base
  has_many :attachments, as: :attachable
  accepts_nested_attributes_for :attachments
end

在我的文档.rb

class Document < ActiveRecord::Base
      has_many :attachments, as: :attachable
      accepts_nested_attributes_for :attachments
end

我的要求是,当我保存我的个人资料时,它将仅验证图像格式,而当我保存文档时,它将仅验证应用程序格式。请指导我如何解决这个问题。

4

1 回答 1

1

附件.rb

validates_attachment :attach, :presence => true, :with => %r{\.(jpeg|jpg|png)$}i, :if => Proc.new{|f| f.attachable_type == 'Profile' }
于 2015-06-09T06:18:39.940 回答