【问题标题】:How to validate "file_fields" in rails 3如何在 Rails 3 中验证“file_fields”
【发布时间】:2011-05-18 07:09:30
【问题描述】:

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

我错过了什么吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 validation filefield


    【解决方案1】:

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

    例如,使用回形针。你会发现

    validates_attachment_size :upload, :less_than => 2.megabytes
    

    并更改您的代码

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

    【讨论】:

      猜你喜欢
      • 2014-06-09
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      相关资源
      最近更新 更多