Topic: How to access a file selected through a form in Ruby on Rails?

I have the following Ruby code which sets up a form to select a file:

    <%= form_for :import, :url=>{:controller=>"products", :action=>"import"}, :html => { :multipart => true } do |f| %>
        <div class= "field">
            <%= f.file_field :import %>
            <%= submit_tag 'Import' %>
        </div>

In the controller, I am trying to call the file that was selected from the local drive. This line works for a specific file:

    book = Spreadsheet.open 'c:/source.xls'

But I don't know how to call up in a controller the file that was selected from the form.

Any ideas?

Last edited by devrwj (2012-09-30 21:17:36)

Re: How to access a file selected through a form in Ruby on Rails?

Can I suggest you use the paperclip gem.
There is a railscast here that might get you on your way
http://railscasts.com/episodes/134-paperclip

It's an old cast but the principles have changed very little. It's a well supported and highly respected gem that will allow you to easily upload files and retrieve them.

There is also a brand new railscast that does things slightly differently using different gems here
http://railscasts.com/episodes/383-uplo … -amazon-s3

Well worth a look.

Both solutions solve your problem of being able to easily retrieve a previously uploaded file with very little work involved.

There are many other solutions to this not least of which is CarrierWave for which there is also a railscast here http://railscasts.com/episodes/253-carr … le-uploads

Personally I didn't get on that well with carrier wave but it's moved on a long way since I last used it so feel free ignore my opinion on that particular gem.

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)

Re: How to access a file selected through a form in Ruby on Rails?

Thanks for the help.

I did implement carrierwave successfully.

Here's the code that now works perfectly for importing data from an Excel spreadsheet:

def import
    require 'spreadsheet'
    Spreadsheet.client_encoding = 'UTF-8'
    import_file = params[ :import ][ :import ]
    file = FileUploader.new
    file.store!(import_file)
    book = Spreadsheet.open "#{file.store_path}"
    sheet1 = book.worksheet 0
    sheet1.each 1 do |row|
        @product = Product.new(:code => row[0], :name => row[1], :status => row[2], :account => current_user.account).save
  end