【问题标题】:Uploading image with paperclip using form_tag使用 form_tag 上传带有回形针的图像
【发布时间】:2013-12-27 14:15:50
【问题描述】:

我正在尝试使用 form_tag 上传图片并使用回形针 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

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

【问题讨论】:

  • 您使用的是Rails 3 还是4
  • 我使用的是 Rails 4。我只是注意到 image = Image.new() 后跟 image.save 的结果是 false,不管分配 image.avatar 什么。
  • 也添加您的controller code
  • 控制器代码在第 4 步提供)。我应该粘贴所有文件而不是特定的 POST 处理程序吗?
  • 好吧,我的猜测是:你 permit :avatar: 在你的 image_params 中了吗?见:controller sectionRails 4github.com/thoughtbot/paperclip

标签: ruby-on-rails ruby paperclip


【解决方案1】:

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

image.save!

【讨论】:

    【解决方案2】:

    问题在于没有

    gem 'protected_attributes'
    

    在 Gemfile 中。包含它之后就可以了。

    【讨论】:

      猜你喜欢
      • 2014-10-13
      • 2011-05-06
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2017-08-26
      • 2012-07-03
      • 1970-01-01
      相关资源
      最近更新 更多