我正在尝试允许POST到包含多个图像的rails中的JSON API。我一直无法通过has_many而不是nested_attributes查找与API上传相关的信息。
我从控制器的参数中得到了这个。
{"component_1"=>
#<ActionDispatch::Http::UploadedFile:0x007f8b4b5ac188
@content_type="image/png",
@headers=
"Content-Disposition: form-data; name=\"images[component_1]\"; filename=\"test.png\"\r\nContent-Type: image/png\r\nContent-Length: 2125\r\n",
@original_filename="test.png",
@tempfile=
#<File:/var/folders/t_/991c5xb934q_d6z13gg__7br0000gn/T/RackMultipart20130531-45537-dywznr>>,
"component_2"=>
#<ActionDispatch::Http::UploadedFile:0x007f8b4b5ac0e8
@content_type="image/png",
@headers=
"Content-Disposition: form-data; name=\"images[component_2]\"; filename=\"icon.png\"\r\nContent-Type: image/png\r\nContent-Length: 4235\r\n",
@original_filename="icon.png",
@tempfile=
#<File:/var/folders/t_/991c5xb934q_d6z13gg__7br0000gn/T/RackMultipart20130531-45537-ju4uy>>
}
我有一个定义了上传者的模型。
如何实际保存UploadedFiles中的图像?此外,我想重命名它们,我不希望在存储图像后出现任何临时文件。
答案 0 :(得分:1)
如果没有看到您的控制器或型号代码,很难发表评论,但话虽如此,答案应该非常直接。
假设您有一个Image模型,并在image_file列上安装了上传器。如果要在控制器中创建新的Image对象,则对所上传的每个图像组件执行Image.create(image_file: params[:component_<number>])
之类的操作。这应该让你知道它是如何工作的,但它们可能是更优雅的方法(nested_attributes for one)