我正在使用 ajax 将数据提交到没有表单的后端,并且一直遇到将参数列入白名单的问题。
我的观点是这样的:
<div class="upload-file"></div>
<div id="file-uppy-item"></div>
这会触发一个 application.js 文件:
document.addEventListener('turbolinks:load', () => {
document.querySelectorAll('.upload-file').forEach(fileInput => {
fileUpload(fileInput)
})
})
调用fileUpload.js:
import 'uppy/dist/uppy.min.css'
import '@uppy/core/dist/style.min.css'
import '@uppy/webcam/dist/style.min.css'
import {
Core,
Dashboard,
Webcam,
AwsS3,
} from 'uppy'
function fileUpload(fileInput) {
const hiddenInput = document.querySelector('.upload-data')
if (document.body.contains(document.getElementById("file-uppy-item"))) {
const a = Core({
debug: true,
id: 'a',
autoProceed: true,
allowMultipleUploads: true,
restrictions: {
maxFileSize: 10000000,
maxNumberOfFiles: 10,
allowedFileTypes: ['image/jpeg', 'image/png']
}
})
.use(Dashboard, {
inline: true,
target: '#file-uppy-item',
trigger: '.upload-file',
hideUploadButton: true,
replaceTargetContent: false,
showProgressDetails: true,
width: 1200,
height: 400,
})
.use(Webcam, {
target: Dashboard,
})
.use(AwsS3, {
companionUrl: '/',
})
a.on('upload-success', (file, response) => {
// construct uploaded file data in the format that Shrine expects
console.log('hi!!!')
const uploadedFileData = {
id: file.meta['key'].match(/^cache\/(.+)/)[1], // object key without prefix
storage: 'cache',
metadata: {
size: file.size,
filename: file.name,
mime_type: file.type,
}
}
$.ajax({
type: "POST",
url: 'photos',
data: {
photo: {
image: uploadedFileData
}
}
})
hiddenInput.value = JSON.stringify(uploadedFileData)
})
}
}
路线如下所示:
resources :items, path: 'art' do
member do
resource :photos, only: :create
get :add_photos
end
end
控制器是这样的:
ItemsController
def create
@item = Item.unapproved.friendly.find(params[:id])
@photo = Photo.create(photo_params)
if @photo.save
respond_to do |format|
format.html { redirect_to root_path, notice: "Thanks! You will be notified when your submission is approved." }
end
else
respond_to do |format|
format.html { redirect_to new_photos_path(@item), :flash => { :error => @photo.errors.full_messages.join(', ') }}
end
end
end
private
def photo_params
params.require(:photo).permit(:image)
end
end
参数提交如下:
Started POST "/art/abcd/photos"
Parameters: {
"photo"=>{
"user_id"=>"1", "image"=>{
"id"=>"d9b406f0e2f10b4ba0154ab31be28c8b.png", "storage"=>"cache", "metadata"=>{
"size"=>"24875", "filename"=>"l.png", "mime_type"=>"image/png"
}
}
}, "id"=>"abcd"
}
然而我总是得到这个:Unpermitted parameter: :image
。为什么白名单不起作用?