【问题标题】:Carrierwave Rails 4 param is missing or the value is empty: image validates_presence modelCarrierwave Rails 4 参数缺失或值为空:图像 validates_presence 模型
【发布时间】:2016-02-16 18:06:35
【问题描述】:

我正在尝试上传图片,并按照tutorial 了解如何上传,现在我正在对其进行扩充以满足我未来的需求。

我的问题是,我正在尝试创建一个模型,您唯一要做的就是上传图片,但如果您点击保存并且图片不存在,那么您将留在原地并收到错误警告.

我得到的错误信息是这样的:

ActionController::ParameterMissing in ImagesController#create
param is missing or the value is empty: image

Extracted source (around line #72):

70 71 72 73 74

    # Never trust parameters from the scary internet, only allow the white list through.
    def image_params
        params.require(:image).permit(:image, :remove_image)
    end

结束

所以我承认我在这里做了一件有点令人困惑的事情,将其中一列命名为与我的模型相同的东西,所以这是我的代码:

image.rb 即图像模型:

class Image < ActiveRecord::Base
mount_uploader :image, ImageUploader
validates_presence_of :image
validate :image_size_validation
validates :image, presence: true

private
    def image_size_validation
        errors[:image] << "should be less than 500KB" if image.size > 0.5.megabytes
    end

结束

Image Controller,只是create方法:

    def create
    @image = Image.new(image_params)

    respond_to do |format|
        if @image.save
            format.html { redirect_to @image, notice: 'Image was successfully created.' }
            format.json { render :show, status: :created, location: @image }
        else
            format.html { render :new }
            format.json { render json: @image.errors, status: :unprocessable_entity }
        end
    end
end

我认为validates :image, presence: true 可以解决我的问题,但我在这里寻求帮助。这是我第一次尝试上传图片/文件,所以无论您能给我什么帮助,我们都非常感激。

谢谢

【问题讨论】:

    标签: validation ruby-on-rails-4 carrierwave params actioncontroller


    【解决方案1】:

    我也遇到过类似的问题。将列名更改为与表名不同的名称为我解决了这个问题。不要在强大的参数和安装上传器的位置更改它。如果这不起作用,您应该共享表单的代码。

    【讨论】:

    • 发布后,我发现了这个问题/答案:stackoverflow.com/questions/17937112/… 我不确定这是否正是我想要的,但它对我有用:我最终将我的参数更改为:def image_params params.fetch(:image, {}).permit(:image, :remove_image) 结束
    猜你喜欢
    • 1970-01-01
    • 2014-08-06
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多