简体   繁体   中英

Unable to permit :file param in rails controller when trying to upload file using active storage

I'm running into a strange issue I've never seen before when setting up active storage where the file param isn't being permitted in my controller.

Here's my model

class Upload < ApplicationRecord
  has_one_attached :file
  # ...removed for brevity
end

And the create method in my controller

class Api::V1::Agent::UploadsController < Api::V1::AgentController
  # ...removed for brevity

  # POST /uploads
  def create
    @upload = Upload.new(upload_params)

    if @upload.save
      render json: @upload, status: :created, location: @upload
    else
      render json: @upload.errors, status: :unprocessable_entity
    end
  end

  private

    # Only allow a trusted parameter "white list" through.
    def upload_params
      params.require(:upload).permit(:company_id, :employee_id, :title, :tags, :secure, :file)
    end
end

Here's what the params object looks like before calling require and permit .

<ActionController::Parameters {"company_id"=>1, "employee_id"=>"", "title"=>"Testing", "file"=>{"rawFile"=>{"path"=>"teams-icon.png"}, "src"=>"blob:http://localhost:3000/cee6f897-8a93-4e27-ab8e-724e6ec60f29", "title"=>"teams-icon.png"}, "format"=>:json, "controller"=>"api/v1/agent/uploads", "action"=>"create", "upload"=><ActionController::Parameters {"company_id"=>1, "employee_id"=>"", "title"=>"Testing s3 storage"} permitted: false>} permitted: false>

And then after

<ActionController::Parameters {"company_id"=>1, "employee_id"=>"", "title"=>"Testing s3 storage"} permitted: true>

If I throw a Pry breakpoint in #create I can call @upload.file and see the virtual file attribute, but for some reason the :file param isn't being permitted.

EDIT:

I've tried permitting the file param as a hash like so params.require(:upload).permit(file: {}) and got the same result.

I also tried submitting the file as just a blob url string (eg {"company_id"=>1, "employee_id"=>"", "title"=>"Testing", "file"=>"blob:http://localhost:3000/1e72ade4-97fc-4535-88e9-45884bcd9633"} instead of the nested hash but :file is still dropped from the permitted params.

params[:file] 是一个散列,所以你必须使用一些不同的方式来允许它

params.require(:upload).permit(:company_id, :employee_id, :title, :tags, :secure, file: {})

The correct way to permit seems to be as a Array:

params.require(:upload).permit(:company_id, :employee_id, :title, :tags, :secure, file: [])

It works this way in the app I'm working on currently and is also how its documented in the rails doc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM