How to validate “file_fields” in rails 3

时光怂恿深爱的人放手 提交于 2019-12-11 17:54:45

问题


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?


回答1:


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'%>



回答2:


Which file upload gem are you using ? If you are using Carrierwave then check this link https://github.com/carrierwaveuploader/carrierwave/wiki/How-to%3A-Validate-attachment-file-size



来源:https://stackoverflow.com/questions/6041086/how-to-validate-file-fields-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!