回形针 - 无法上传图片

时间:2015-09-22 18:52:27

标签: ruby-on-rails image paperclip

模型

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

我选择要上传的图片,填写文字,提交,然后我收到错误消息&#34;此字段[图片]不能为空白&#34;虽然它真的没有。哪里可能是问题?

2 个答案:

答案 0 :(得分:3)

问题在于你没有允许该参数被访问,这样做 在控制器参数require中添加:image 参数,以便您可以访问它,如下所示:

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

答案 1 :(得分: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
相关问题