到目前为止,我已设法上传文件:
# In new.html.erb <%= file_field_tag 'upload[file]' %>
并访问控制器中的文件
# In controller#create @text = params[:upload][:file]
解决方法
完整的例子
例如,上传包含联系人的导入文件.您不需要存储此导入文件,只需处理它并将其丢弃即可.
路线
的routes.rb
resources :contacts do collection do get 'import/new',to: :new_import # import_new_contacts_path post :import # import_contacts_path end end
形成
意见/联系人/ new_import.html.erb
<%= form_for @contacts,url: import_contacts_path,html: { multipart: true } do |f| %> <%= f.file_field :import_file %> <% end %>
调节器
控制器/ contacts_controller.rb
def new_import end def import begin Contact.import( params[:contacts][:import_file] ) flash[:success] = "<strong>Contacts Imported!</strong>" redirect_to contacts_path rescue => exception flash[:error] = "There was a problem importing that contacts file.<br> <strong>#{exception.message}</strong><br>" redirect_to import_new_contacts_path end end
联系型号
车型/ contact.rb
def import import_file File.foreach( import_file.path ).with_index do |line,index| # Process each line. # For any errors just raise an error with a message like this: # raise "There is a duplicate in row #{index + 1}." # And your controller will redirect the user and show a flash message. end end
希望有所帮助!
约书亚