Re: Handling File on Upload

Vladimir Rybas
2010-12-06T19:47:29Z

I recommend you to use Paperclip for files uploading.
http://railscasts.com/episodes/134-paperclip

Besides it''s other awesome features, you want to use Paperclip
Processors to play with a file after upload.
http://mdeering.com/posts/018-paperclip-processors-doing-so-much-more-with-your-attachment

To read file lines you can go for

File.readlines(@file.path).collect(&:chomp).each do |line|
 ... (create your models here)
end

to collect all lines.
`chomp` will cut end-of-line symbols, and @file it''s an object which
is given by Paperclip.
Or if you have troubles with this one, here''s another option

IO.foreach("path/to/file.txt") do |line|
 ... (create your models here)
end


On Mon, Dec 6, 2010 at 5:54 AM, spncrgr
<thisbudsforyou1-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:
> Hello,
>
> I need some help trying to figure out how to add the ability for a
> user to upload a text file, and then have the application parse that
> text file, and add each record as instance of a model object.
 I''ve
> found a lot of helpful articles out there, but I''m stuck trying to
> bring it all together since I''m still very new to all of this.
>
> Here''s my view code:
> # index.html.erb
> <% form_for :upload, :url => { :action => :upload }, :html =>
> { :multipart => true } do |f| %>
>
> Please select a file to upload:
>    <%= f.file_field :file %>
>    <%= f.submit ''Upload'', :disable_with =>
"Uploading..." %>
>
> <% end %>
>
> In my controller, I''ve been able to write something like this to
work
> with the data in my upload view:
>
> # mailing_lists_controller.rb
> def upload
>    file = params[:upload][:file]
>    @data = file.read
>  end
>
> so then the view looks like this:
> # upload.html.erb
> <% @data.split("\r\n").each do |row| %>
>
>    <%= row.split("\t").join(" | ") %>
>
> <% end %>
>
>
> So, where I''m stuck is translating that into saving each row as a
> record in the database.  I''ve tried several different things in
the
> model (like creating a "process" method or using
"before_save"), but
> nothing has been successful thus far (probably because I''m not
> implementing it correctly).
>
> Any help would be appreciated.
>
> Thanks,
> Spencer
>
> --
> You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
> To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
> To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@googlegroups.com.
> For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.
>
>

--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@googlegroups.com.