如何验证"file_fields"在铁轨3 [英] How to validate "file_fields" in rails 3
本文介绍了如何验证"file_fields"在铁轨3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Rails的新手,请引导我.
i am a newbie for rails, please guide me.
我想验证"file_field"用于图像上传. 只能上传jpg/png/gif,并且可以上传特定尺寸,例如最大尺寸(500x500)
i want to validate "file_field" for image upload. just jpg/png/gif can be upload and specific size like max size (500x500)
这是我的_form.html.erb
this is my _form.html.erb
<%= form_for(@photo, :html => {:multipart => true} ) do |f| %>
<% if @photo.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@photo.errors.count, "error") %> prohibited this photo from being saved:</h2>
<ul>
<% @photo.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description, :size => '115x20' %>
</div>
<div class="field">
<label for="image_file">File</label><br />
<%= file_field 'upload', 'datafile'%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我试图像这样进行验证
class Photo < ActiveRecord::Base
validates_presence_of :title, :description, :upload
validates_uniqueness_of :title
validates_format_of :upload, :allow_blank => false,
:with => %r{\.(gif|jpg|png)$}i,
:message => 'must be a URL for GIF, JPG ' +
'or PNG image.'
end
错误就这样
undefined method `upload' for #<Photo:0xad6b294>
我错过了什么吗?
推荐答案
如果您使用任何照片上传插件,都会发现使用它的validates方法
if you are using any photo upload plugin, you will find validates methods with it
例如,使用papaerclip.您会发现
for example ,using papaerclip. you will find
validates_attachment_size :upload, :less_than => 2.megabytes
并更改您的代码
<%= file_field 'upload', 'datafile'%> to <%= f.file_field :upload, 'datafile'%>
这篇关于如何验证"file_fields"在铁轨3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文