使用form_tag使用回形针上传图像

时间:2013-12-26 19:17:03

标签: ruby-on-rails ruby paperclip

我正在尝试使用form_tag进行图片上传,并使用paperclip gem保存。我一开始就陷入困境。

1)我创建了这样的模型图像:

class Image < ActiveRecord::Base
  has_attached_file :avatar, :styles => { :medium => "512x512>", :thumb => "128x128>" }, :default_url => "/images/:style/missing.png"
  validates_attachment :avatar, :presence => true,
                                :content_type => { :content_type => ["image/jpg", "image/gif", "image/png"] },
                                :size => { :in => 0..512.kilobytes }
end

2)进行了这样的迁移:

class AddFileToImageModel < ActiveRecord::Migration
  def self.up
    add_attachment :images, :avatar
  end

  def self.down
    remove_attachment :images, :avatar
  end
end

3)在视图中制作:

<%= form_tag '/index_page/submitImage', multipart: true } do %>
    <%=file_field_tag( :avatar, class: 'image_file_input' )%>
<%= submit_tag 'Submit image', class: 'button large'%>
<%end%>

4)为此表单制作了POST处理程序,如下所示:

image = Image.new( )
image.avatar = params[ :avatar ]
if ( image.save )
    flash[ :success ] = "image saved"
else
    flash[ :error ] = "Image upload failed!"
end
redirect_to index_page_path

5)当我在表单中选择文件并按“提交图像”按钮时,我得到“image.save”行失败。日志内容如下:

Started POST "/index_page/submitImage" for 127.0.0.1 at 2013-12-26 23:10:08 +0400
Processing by StaticPagesController#submitImage as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ufwOW9OcNcrBISGdEfwixmEonszIKNAtBlc4AqvK5OY=", "avatar"=>#<ActionDispatch::Http::UploadedFile:0xb5fdea98 @tempfile=#<File:/tmp/RackMultipart20131226-4639-11qvysd>, @original_filename="back.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"avatar\"; filename=\"back.jpg\"\r\nContent-Type: image/jpeg\r\n">, "commit"=>"Submit image"}
  [1m[35m (0.5ms)[0m  begin transaction
  [1m[36m (0.4ms)[0m  [1mrollback transaction[0m
Redirected to http://localhost:3000/index_page/index

数据库确实包含所有迁移,包括回形针字段。我错过了什么?

2 个答案:

答案 0 :(得分:0)

使用bang方法保存以找出确切的错误

image.save!

答案 1 :(得分:0)

问题在于没有

gem 'protected_attributes'
Gemfile中的

。包括它之后就可以了。