I am relatively new to rails cannot get the following code to work. I am trying to upload a data file (Excel or csv), copy it to a temp folder and create a record in a Datafiles model which holds basic file information, such as filename, type, and date. Then I want to read the file and use the data to create or update records in several other models. If all goes well, move the file to a permanent location and write the new path in the Datafiles record.
Controller:
def new
  @datafile = Datafile.new
  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @datafile }
  end
end
def create
  @datafile = Datafile.new(params[:upload])
  @datafile.save!
  redirect_to datafile_path(@datafile), :notice => "Successfully imported datafile"
rescue => e
  logger.error( 'Upload failed. ' + e.to_s )
  flash[:error] = 'Upload failed. Please try again.'
  render :action => 'new'
end
View:
<%= form_for @datafile, :html => {:multipart => true} do |f| %>
  <p>
    <%= f.label(:upload, "Select File:") %>
    <%= f.file_field :upload %>
  </p>
  <p> <%= f.submit "Import" %> </p>
<% end %&g开发者_开发技巧t;
Model:
require 'spreadsheet'
class Datafile < ActiveRecord::Base
  attr_accessor :upload
  attr_accessible :upload
  before_create :upload_file
  def upload_file
    begin
      File.open(Rails.root.join('uploads/temp', upload.original_filename), 'wb') do |file|
        file.write(upload.read)
        self.filename = upload.original_filename
        Spreadsheet.client_encoding = 'UTF-8'
        @book = Spreadsheet.open(file.path)
        self.import
      end          
    rescue => e
      @upload_path = Rails.root.join('uploads/temp', upload.original_filename)
      File.delete(@upload_path) if File::exists?(@upload_path)
      raise e
    end
  end
  def import
    case @book.worksheet(0).row(0)[0]
      when "WIP Report - Inception to Date"
      self.report_type = 'WIP'
      puts 'report_type assigned'
      self.import_wip
      else
      self.report_type = 'Unknown'
    end
  end  
  def import_wip
    self.end_date = @book.worksheet(0).row(0)[3]
    puts 'end_date assigned'
  end
  def formatted_end_date
   end_date.strftime("%d %b, %Y")
  end
end
However, it fails and the rails server window says
Started POST "/datafiles" for 127.0.0.1 at 2011-05-24 16:05:25 +0200
  Processing by DatafilesController#create as HTML
  Parameters: {"utf8"=>"✓", "datafile"=>{"upload"=>#<ActionDispatch::Http::UploadedFile:0xa0282d0 @original_filename="wip.xls", @content_type="application/vnd.ms-excel", @headers="Content-Disposition: form-data; name=\"datafile[upload]\"; filename=\"wip.xls\"\r\nContent-Type: application/vnd.ms-excel\r\n", @tempfile=#<File:/tmp/RackMultipart20110524-14236-1kcu3hm>>}, "commit"=>"Import"}
Upload failed. undefined method `original_filename' for nil:NilClass
Rendered datafiles/new.html.erb within layouts/application (54.5ms)
Completed 200 OK in 131ms (Views: 56.3ms | ActiveRecord: 0.0ms)
I have rspec model tests that pass and controller tests that fail to redirect after saving. I can post them if it would be useful.
I inserted the raise @datafile.to_yaml and got the following in the terminal.
ERROR RuntimeError: --- !ruby/object:Datafile 
attributes: 
  filename: 
  report_type: 
  import_successful: 
  project: 
  begin_date: 
  end_date: 
  created_at: 
  updated_at: 
attributes_cache: {}
changed_attributes: {}
destroyed: false
marked_for_destruction: false
persisted: false
previously_changed: {}
readonly: false
I notice that :upload is not listed. Can I set model instance variables from the form? :upload is an instance variable, not an attribute, because I do not want to keep the uploaded file in the database (just its path to the local directory). If I cannot set instance variables in the view's form, any suggestions? Does it make sense (in terms of MVC) to upload the file to a temp folder in the controller, then create a model record by passing it the temp file's path?
Hello I am pretty new to Rails and was strugling with this as well I found a solution though it probably isn't the best. It does work though.
in you model make a public function called import_upload
def import_upload( upload ) 
  @uploaded_file = upload
end
now in your controller you can explicitly pass it. I don't know why this doesn't happen automatically if you make an attr_accsessor with the same name as the file_field but this was the solution that worked for me.
def new
  foo = Foo.new( params[:foo] )
  foo.import_upload( params[:foo][:uploaded_file] ) #This is were the majic happens
  #Do your saving stuff and call it a day
end
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论