我与配置文件和文档表的附件模型有多态关联。我在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
和我的个人资料.rb
class Profile < ActiveRecord::Base
has_many :attachments, as: :attachable
accepts_nested_attributes_for :attachments
end
在我的document.rb
中class Document < ActiveRecord::Base
has_many :attachments, as: :attachable
accepts_nested_attributes_for :attachments
end
我的要求是当我保存我的个人资料时,它将仅验证图像格式,当我保存文档时,它将仅验证应用程序格式。请指导我如何解决这个问题。
答案 0 :(得分:1)
attachment.rb
validates_attachment :attach, :presence => true, :with => %r{\.(jpeg|jpg|png)$}i, :if => Proc.new{|f| f.attachable_type == 'Profile' }