0

我是rails的新手,请指导我。

我想为图像上传验证“file_field”。只能上传 jpg/png/gif 和特定尺寸,例如最大尺寸 (500x500)

这是我的 _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>

我错过了什么吗?

4

1 回答 1

0

如果你使用任何照片上传插件,你会发现它的验证方法

例如,使用回形针。你会找到

validates_attachment_size :upload, :less_than => 2.megabytes

并更改您的代码

<%= file_field 'upload', 'datafile'%> to <%= f.file_field :upload, 'datafile'%>
于 2011-05-18T07:28:51.733 回答