【问题标题】:Paperclip - Can't upload a picture回形针 - 无法上传图片
【发布时间】:2015-09-22 18:52:27
【问题描述】:

型号

class Pin < ActiveRecord::Base
    attr_accessible :description, :image
    has_attached_file :image, styles: { medium: "320x240>"}

    validates :description, presence: true
    validates :user_id, presence: true
    validates_attachment :image, presence: true,
                        content_type: { content_type: ["image/jpeg", "image/jpg", "image/gif", "image/png"] },
                        size: { in: 0..5.megabytes }


    belongs_to :user

end

我选择了我要上传的图片,填写文本并提交,然后我收到错误消息“此字段 [图片] 不能为空白”,尽管实际上并非如此。问题可能出在哪里?

【问题讨论】:

  • 您的控制器中允许哪些参数以及什么版本的 Rails?
  • 显示您的表单代码和通过请求发送的数据的哈希值。

标签: ruby-on-rails image paperclip


【解决方案1】:

问题是您不允许访问该参数,这样做 在控制器参数要求中添加 :image 参数,以便您可以访问它,如下所示:

params.require(:pin).permit(YOUR PARAMETERS HERE, :image)

【讨论】:

  • 谢谢,我不知道我必须这样做。它可能解决了这个问题,但是现在如果我尝试上传图像,我的控制台会发疯,它会滞后我的 web 应用程序一分钟,并且我收到此错误消息“内容与报告的内容不同”。我什至从未见过这个错误。
  • 这是另一个问题,与您发布的内容不同,建议您阅读此链接(github.com/thoughtbot/paperclip/issues/1924)。
【解决方案2】:

听起来您可能没有将您的file_field 姓名列入白名单。我不确定您使用的是哪个版本的 Rails,所以我将提供并回答 3 和 4。

在你看来:

<%= form_for @pin do |f| %>
    <%= f.file_field :image %>
<% end %>

在您的控制器中:

Rails 4

def create
    @pin = Pin.new(pin_params)

    if @pin.save
       # do your success calls here
    else
       # do your error calls here
    end
end

private
def pin_params
    # whitelist it here with "Strong Parameters" if you're using Rails 4
    params.require(:pin).permit(:image)
end

如果使用 Rails 3

# ==== Pin.rb model ====
# whitelist it in your model with attr_accessible
class Pin < ActiveRecord::Base
    attr_accessible :image

    validates :description, presence: true
    validates :user_id, presence: true
    validates_attachment :image, presence: true,
                    content_type: { content_type: ["image/jpeg", "image/jpg", "image/gif", "image/png"] },
                    size: { in: 0..5.megabytes }

    belongs_to :user
end

#===== PinsController.rb =======
def create
    @pin = Pin.new(params[:image])

    if @pin.save
       # do your success calls here
    else
       # do your error calls here
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-03
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 2011-01-08
    • 2015-05-09
    • 2013-09-09
    相关资源
    最近更新 更多