我新的軌道,並想有一個問題回答:Ruby on Rails的上傳與空文件字段按鈕
我有我的形式,其工作完全正常上傳CSV場當我真正上傳文件。但是當我在沒有附加文件的情況下點擊上傳按鈕時,我得到一個異常:對於nil:NilClass,未定義的方法`[]'。有沒有辦法留在同一頁面,而是顯示「沒有文件上傳」的警告?
我試過做if(params[:model][:file].nil?) redirect_to model_path end
但它繼續其餘的代碼。先謝謝您的幫助。
查看代碼:
<%= form_for (@model), :url=>{ :controller=>"models", :action => 'create'}, :html=>{:multipart => true} do |f| %>
<p><%= f.label :file, 'Import csv file' %><br/>
<%= f.file_field :file, :accept => "text/csv"%></p>
<%= submit_tag "Upload" %>
<% end %>
Controller Code:
def create
51 @model = Model.new
52
53 @model.date_created = Time.now.utc
54
55
56 #handles csv input
59 if(params[:model][:file])
60
61 @model.id = SecureRandom.uuid;
62 file_data = params[:model][:file].read
63 @parsed_file = CSV.parse(file_data)
64 n=0
65 @parsed_file.each do |row|
74
75 if @model.save
76 n=n+1
77 end
79 end
81 else
82 @model.id = "different type"
83 end
84
85 respond_to do |format|
86 if @model.save
87 if(params[:model][:file])
88 format.html { redirect_to @model, :notice => "Successfully imported the CSV file. #{n} new records added to the database" }
89 else
90 format.html { redirect_to @model, notice: 'Model entry was successfully created.' }
91 end
92 format.json { render json: @model, status: :created, location: @model }
93 else
94 format.html { render action: "new" }
95 format.json { render json: @model.errors, status: :unprocessable_entity }
96 end
你需要顯示一些代碼,任何人都可以幫你做到這一點。除此之外,你調用的方法必須是空的,這就是爲什麼你得到這個錯誤 – David