尝试使用Rails和Carrierwave上传文件时,我一直遇到params错误。没有关联,没有多态,只是一个简单的附件模型,它什么都不属于:
控制器:
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
日志:
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)
使用型号更新了:
class Attachment < ActiveRecord::Base
mount_uploader :file, FileUploader
end
者:
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
答案 0 :(得分:3)
只需更改
params.require(:attachment).permit(:file)
带
params.require(:attachment).permit(:attachment)
因为您收到参数:"attachment"=>{"attachment"=>#<ActionDispatc ...
我看不到你的观点,但我猜你这样做了:
<%= f.file_field :attachment %>
而不是:
<%= f.file_field :file %>
如果是,请修复视图并允许:文件。