The Whiz of Oz
The Whiz of Oz

Reputation: 7043

Unpermitted parameter with Carrierwave

I keep getting a params error when trying to upload a file with Rails and Carrierwave. No associations, nothing polymorphic, just a simple Attachment model, that belongs to nothing:

controller:

class AttachmentsController < ApplicationController

def create
  @attachment = Attachment.new(attachment_params)
    if @attachment.save
      flash.now[:notice] = 'Done!'
      redirect_to root_path
    else
      flash.now[:error] = 'Error.'
      redirect_to root_path
    end
end

private

    def attachment_params
      params.require(:attachment).permit(:file)
    end

log:

Started POST "/attachments" for 127.0.0.1 at 2014-11-06 15:11:48 +0300
Processing by AttachmentsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"B3jUUOcHivc4m1SsrveIznfaXbSEnmdah1c1hrhCSe4=", "attachment"=>{"attachment"=>#<ActionDispatch::Http::UploadedFile:0x007f9b31c65b00 @tempfile=#<Tempfile:/var/folders/z7/241wfhj97nx98q3zzkpvj_sm0000gn/T/RackMultipart20141106-4801-1c6vtqz>, @original_filename="нованет 2.xls", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"attachment[attachment]\"; filename=\"\xD0\xBD\xD0\xBE\xD0\xB2\xD0\xB0\xD0\xBD\xD0\xB5\xD1\x82 2.xls\"\r\nContent-Type: application/octet-stream\r\n">}, "commit"=>"Upload my list"}
Unpermitted parameters: attachment
   (0.6ms)  BEGIN
  SQL (0.7ms)  INSERT INTO "attachments" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id"  [["created_at", "2014-11-06 12:11:48.966191"], ["updated_at", "2014-11-06 12:11:48.966191"]]
   (0.4ms)  COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 29ms (ActiveRecord: 1.8ms)

Updated with model:

class Attachment < ActiveRecord::Base
  mount_uploader :file, FileUploader
end

Uploader:

class FileUploader < CarrierWave::Uploader::Base

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def extension_white_list
    %w(pdf xls xlsx csv txt doc docx)
  end

end

Upvotes: 0

Views: 1519

Answers (1)

Alejandro Babio
Alejandro Babio

Reputation: 5229

Just change

params.require(:attachment).permit(:file)

with

params.require(:attachment).permit(:attachment)

Because you receive parameters: "attachment"=>{"attachment"=>#<ActionDispatc ...

I don't see your view, but I guess you are doing this:

<%= f.file_field :attachment %>

Instead of:

<%= f.file_field :file %>

If you are, fix the view and permit :file.

Upvotes: 3

Related Questions