无法解析create方法中的参数(文件上传)

时间:2019-04-03 10:18:08

标签: ruby-on-rails

我有一个create方法,该方法应该收集文件参数并将文件保存在公用文件夹中。我可以看到正在通过控制台处理的文件详细信息,但是方法的第一行崩溃了

以下是控制台上表单提交的日志(我已经上传了两个文件):

Processing by GroupmeetingsController#create as JSON
  Parameters: {"authenticity_token"=>"rsuhfN4HXxd/RG1ZfdmbE2+8T0SC927wC8H5hFI+wYeGUoF9wfWfG3AmiT9nWROauamHM3JsFyS/Hu7fH0RH9g==", "file"=>{"0"=>#<ActionDispatch::Http::UploadedFile:0x00007f9743f68ab0 @tempfile=#<Tempfile:/var/folders/c_/cqbnlqbx5lq7vjgf31_wsgvh0000gp/T/RackMultipart20190403-7204-1a88kpp.JPG>, @original_filename="IMG_8009.JPG", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file[0]\"; filename=\"IMG_8009.JPG\"\r\nContent-Type: image/jpeg\r\n">, "1"=>#<ActionDispatch::Http::UploadedFile:0x00007f9743f689e8 @tempfile=#<Tempfile:/var/folders/c_/cqbnlqbx5lq7vjgf31_wsgvh0000gp/T/RackMultipart20190403-7204-1fjmx9t.jpg>, @original_filename="Cocoa_Front_tribal.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file[1]\"; filename=\"Cocoa_Front_tribal.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "locale"=>"en"}
  User Load (1.9ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", "bb789076-afd7-43e9-a91c-37ace112183b"], ["LIMIT", 1]]
Completed 500 Internal Server Error in 7ms (ActiveRecord: 1.9ms)



NoMethodError (undefined method `[]' for nil:NilClass):

app/controllers/groupmeetings_controller.rb:53:in `create'

控制器如下所示:

 def create
    hash = params[:file]
    **files_list = JSON.parse(hash) if hash.is_a?(String)**
    groupmeeting = params[:groupmeeting]
    alpha_start = DateTime.strptime(groupmeeting[:start], "%m/%d/%Y %I:%M %P")
    alpha_end = DateTime.strptime(groupmeeting[:end], "%m/%d/%Y %I:%M %P")
    @contact_person = User.where(profile: "1", company: current_user.company)
    @event = current_user.events.build(event_params.merge(start: alpha_start, end: alpha_end))
    Dir.mkdir("#{Rails.root}/public/"+@event.id.to_s)
    files_list.each do |pic|
      File.rename( "#{Rails.root}/"+pic, "#{Rails.root}/public/"+@event.id.to_s+'/'+File.basename(pic))
      product.pics.create(name: pic)
    en

    if @event.save
      redirect_to events_path, notice: "OK! Event is created."
    else
      render 'new'
    end
  end
end

有人知道如何处理文件吗?我正在使用以下教程,但似乎缺少很多: https://www.sitepoint.com/asynchronous-multiple-file-upload-with-rails-and-dropzone-js/

0 个答案:

没有答案