How to validate "file_fields" in rails 3
i am a newbie for rails, please guide me.
i want to validate "file_field" for image upload. just jpg/png/gif can be upload and specific size like max size (500x500)
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 %>
and i 开发者_高级运维tried to make validate like this
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
and the error come like this
undefined method `upload' for #<Photo:0xad6b294>
am i missing something?
if you are using any photo upload plugin, you will find validates methods with it
for example ,using papaerclip. you will find
validates_attachment_size :upload, :less_than => 2.megabytes
and also change your code
<%= file_field 'upload', 'datafile'%> to <%= f.file_field :upload, 'datafile'%>
精彩评论