2011-05-18 27 views
0

我是rails的新手,請指導我。如何驗證rails中的「file_fields」3

我想驗證「file_field」的圖片上傳。 只是JPG/PNG/GIF可以上傳和具體大小像最大尺寸(500×500)

這是我_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> 

我這麼想嗎?

回答

0

如果你使用任何照片上傳插件,你會發現驗證它

方法,例如,使用papaerclip。你會發現

validates_attachment_size :upload, :less_than => 2.megabytes 

,改變你的代碼

<%= file_field 'upload', 'datafile'%> to <%= f.file_field :upload, 'datafile'%> 
+0

thx它的幫助巨型 – 2011-05-18 08:46:26