嗨,我已经给出了我的附件模型:
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
我在我的应用程序中使用这些内容类型,以便我无法更改这些内容类型。所以我决定在控制器站点设置验证。我给了:
def create
@designation = Designation.create(designation_params)
if (@designation.attachment.attach_content_type.present? &&
(@designation.attachment.attach_content_type.to_s =~ /image\/.*/)) || @designationerrorse.present?
redirect_to designations_path, notice: I18n.t('designation_created')
else
render :action => :new
end
end
指定模型中的代码:
has_one :attachment, as: :attachable
accepts_nested_attributes_for :attachment
但它无法正常运行。如果我提交的表单文件字段为空,那么它会给我这个错误:
未定义的方法`attach_content_type'代表nil:NilClass
如何实施这些验证,以便指定只接受图像,如果它是空白的?向我发送错误消息 无法空白 。请指导我。提前谢谢
答案 0 :(得分:1)
validates_attachment :attach, :presence => true, :with => %r{\.(rar|tar|zip)$}i, :size => { :in => 0..10.kilobytes}, :if => Proc.new{|f| f.attachable_type == 'Designation' }
当附件属于指定类
时,将调用此验证答案 1 :(得分:-1)
您可以使用自己的验证方法:
$('#left-slide').children().first().addClass('full-banner');
$('#right-slide').children().first().addClass('full-banner');