我正在制作一个应该将文件上传到PUT
端点的表单。我可以将此文件作为模型实例(tab_community
)的一部分上传,但我收到400错误。我的想法是使用模型控制器的PUT
端点将文件上传到Rails(因为文件上传/导入是更新tab_community
条目的另一种方式),但这可能会产生400错误,因为文件不属于tab_community
模型。
如果我的猜测是正确的,您如何处理不属于原始模型的属性和值?是否有某种方法告诉端点不像通常在请求中有文件时那样更新数据库?如果我猜错了,那就是别的......我做错了什么?
我包括一切都是为了完整......
客户代码:
function import_community(form_data) {
var deferred = $q.defer();
// using 3rd party module
// https://github.com/danialfarid/ng-file-upload
Upload.upload({
url: __env.api_url + ':' + __env.port + '/tab_communities/' + form_data.id + '.json'
, data: form_data
, method: 'PUT'
})
.then(
function(response) {
deferred.resolve(response.data.response);
}
, function(data, status, headers, config) {
deferred.resolve(JSON.parse('{"response": {"method": "PUT", "result": "error", "status": "' + status + '"}}'));
}
);
return deferred.promise;
}
服务器代码:
# PATCH/PUT /tab_communities/1
# PATCH/PUT /tab_communities/1.json
def update
if @tab_community.update(tab_community_params)
render :show, status: :ok, location: @tab_community
else
render json: @tab_community.errors, status: :unprocessable_entity
end
end
错误输出:
Started PUT "/tab_communities/33.json" for 127.0.0.1 at 2017-08-18 16:48:28 -0400
Processing by TabCommunitiesController#update as JSON
Parameters: {"id"=>"33", "name"=>"test_aug_190000", "ref_community_type_id"=>"7", "created_at"=>"2017-08-17T01:56:28.651Z", "updated_at"=>"2017-08-18T19:54:10.494Z", "url"=>"http://localhost:3000/tab_communities/33", "$$hashKey"=>"object:58", "import"=>{"this_file"=>#<ActionDispatch::Http::UploadedFile:0x0000000a527c90 @tempfile=#<Tempfile:C:/Users/joe_t/AppData/Local/Temp/RackMultipart20170818-20396-pmgjwr.csv>, @original_filename="TechVCMembers.csv", @content_type="application/vnd.ms-excel", @headers="Content-Disposition: form-data; name=\"import[this_file]\"; filename=\"TechVCMembers.csv\"\r\nContent-Type: application/vnd.ms-excel\r\n">}}
TabClientSeat Load (0.0ms) SELECT "tab_client_seats".* FROM "tab_client_seats" WHERE "tab_client_seats"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
TabCommunity Load (0.0ms) SELECT "tab_communities".* FROM "tab_communities" WHERE "tab_communities"."id" = $1 LIMIT $2 [["id", 33], ["LIMIT", 1]]
Completed 400 Bad Request in 49ms (ActiveRecord: 5.9ms)
ActionController::ParameterMissing (param is missing or the value is empty: tab_community):
app/controllers/tab_communities_controller.rb:57:in `tab_community_params'
app/controllers/tab_communities_controller.rb:34:in `update'
答案 0 :(得分:1)
这是你的问题:
ActionController::ParameterMissing (param is missing or the value is empty: tab_community):
您的tab_community_params
方法是什么样的?在错误输出中,您尝试上传的文件字段名为import
,而tab_community_params
中缺少该文件字段?