【问题标题】:Validate attachment format for specific models in Rails 4验证 Rails 4 中特定模型的附件格式
【发布时间】:2015-06-09 06:13:21
【问题描述】:

我与带有配置文件和文档表的附件模型具有多态关联。我在 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

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

【问题讨论】:

    标签: ruby-on-rails validation paperclip-validation


    【解决方案1】:

    附件.rb

    validates_attachment :attach, :presence => true, :with => %r{\.(jpeg|jpg|png)$}i, :if => Proc.new{|f| f.attachable_type == 'Profile' }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多