Ruby on rails 验证附件内容类型回形针
是否可以在中强制执行“内容类型”验证而不强制执行“存在”验证(即允许空白)?我目前有:Ruby on rails 验证附件内容类型回形针,ruby-on-rails,paperclip,Ruby On Rails,Paperclip,是否可以在中强制执行“内容类型”验证而不强制执行“存在”验证(即允许空白)?我目前有: class Person < ActiveRecord::Base has_attached_file :picture validates_attachment_content_type :picture, :content_type => ['image/jpeg', 'image/jpg', 'image/png'] end 只有在包含附件的情况下才能进行验证。我不确定该方法是否是
class Person < ActiveRecord::Base
has_attached_file :picture
validates_attachment_content_type :picture, :content_type => ['image/jpeg', 'image/jpg', 'image/png']
end
只有在包含附件的情况下才能进行验证。我不确定该方法是否是导致您失败的原因;这是我的简单课程
class Image < ActiveRecord::Base
has_attached_file :photo, {
:styles => { :large => "700x400#", :medium=>"490x368#", :thumbnail=>"75x75#" },
:default_url => "/images/thumbnail/blank-recipe.png"}
validates_attachment_content_type :photo, :content_type => /image/
end
不过,您可能正在进行其他回形针验证。你能发布一个简单的例子吗?验证内容类型接受
:如果=>Proc.new{{r}!r.content\u type.blank?}
在它的选项哈希中,也许这会解决你的问题
这对我很有效
validates_attachment :image1, :presence => true,
:content_type => { :content_type => "image/jpg" },
:size => { :in => 0..10.kilobytes }
工作示例
在以下模型中,只有image/png、image/gif和image/jpeg是图像附件的有效内容类型
class Photo
has_attached_file :image
validates_attachment_content_type :image,
:content_type => /^image\/(png|gif|jpeg)/
end
规格
更多信息
您还可以查看负责执行验证的类
或者看看它的,其中包含更多示例。我稍微更新了上面的示例代码。当我执行“Person.new.valid”时,结果为false。我正在运行Rails 2.3.8和曲别针2.2.15。如果我理解正确的话
:content\u type=>/image/
表示图像文件类型的列表。您知道该列表包括哪些内容,它存储在回形针代码中的什么位置,以及其他类型的文件(如文档)是否存在这种情况吗?@Btuman Watch out of last
:default_url=>“/images/thumbnail/blank recipe.png”}这将导致错误。
validates_attachment :image1, :presence => true,
:content_type => { :content_type => "image/jpg" },
:size => { :in => 0..10.kilobytes }
class Photo
has_attached_file :image
validates_attachment_content_type :image,
:content_type => /^image\/(png|gif|jpeg)/
end
describe Photo do
it { should validate_attachment_content_type(:image).
allowing('image/png', 'image/gif', 'image/jpeg').
rejecting('text/plain', 'text/xml', 'image/abc', 'some_image/png') }
end