【问题标题】:Paperclip in Rails 4 - Strong Parameters Forbidden Attributes ErrorRails 4中的回形针 - 强参数禁止属性错误
【发布时间】:2013-07-19 03:36:16
【问题描述】:

在 Rails 4 中上传回形针时遇到问题 - ForbiddenAttributesError 失败(强参数验证)。拥有最新的回形针宝石和最新的轨道 4 宝石。

我有一个模型“图像”,模型中有一个附加文件“上传”:

has_attached_file :upload, :styles => { :review => ["1000x1200>", :png], :thumb => ["100x100>", :png]}, :default_url => "/images/:style/missing.png"

图像模型是用脚手架创建的,我添加了回形针迁移。表单部分已更新以使用

f.file_field :upload

表单会生成一组典型的回形针参数,其中包含上传的图像参数。我还在图像模型中传递了一个 transaction_id,所以它应该被允许。仅此而已 - 图像和交易 ID。

我希望能够在我的控制器中编写以下内容以将我的帖子列入白名单 - 但它失败了:

def image_params
  params.require(:image).permit(:transaction_id, :upload)
end

所以我变得更明确了——但这也失败了:

def image_params
  params.require(:image).permit(:transaction_id, :upload => [:tempfile, :original_filename, :content_type, :headers])
end

Rails 4 没有向我显示 ForbiddenAttributesError 在开发环境中失败的原因,这让我有点沮丧——它应该显示错误但它没有——这将是一个很好的补丁来简化开发。或者也许其他人都得到了我错过的东西!非常感谢您的帮助。

【问题讨论】:

    标签: paperclip ruby-on-rails-4 strong-parameters paperclip-validation


    【解决方案1】:

    我了解现在发生的事情 - 并将保留此内容,希望对其他人有所帮助。我正在从 rails 3 项目中移植代码,但错过了创建图像的行:

    @image = current_user.images.new(params[:image])
    

    在 rails 4 中这是不正确的(我相信)。我更新到

    @image = current_user.images.new(image_params)
    

    这解决了我的问题。

    【讨论】:

    • 你最终在你的 params.permit() 中加入了什么来让它工作?
    • 在我的例子中,我有一个带有回形针附件“image_file”的模型“Image”。回形针迁移在数据库中创建了几个列,例如 image_file_file_name 等,但您所要做的就是 params.require(:image).permit(:image_file) 以允许回形针发挥其魔力。
    • 非常感谢!这不直观,但它有效:)
    【解决方案2】:

    看起来你的第一个应该可以工作。这就是我用于我的项目的东西。

    class GalleriesController < ApplicationController
    
      def new
        @gallery = Gallery.new
      end
    
      def create
        @user.galleries.new(gallery_params)
      end
    
      private
    
      #note cover_image is the name of paperclips attachment filetype(s)
      def gallery_params
        params.require(:gallery).permit(:cover_image)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 2012-12-11
      • 1970-01-01
      相关资源
      最近更新 更多