On Jul 31, 2006, at 2:08 PM, Mike Williams wrote:
Hi everybody,
I know this is an easy question but I don’t seem to see the solution.
I’m trying to have a user select a file so that my code can parse
it and
populate the database with corresponding values. So far it seems like
uploads but nothing shows in my db. Can anybody give me a hand?
Mike-
I answered this question fior either you or maybe someone you work
with already> I am pasting my response here again:
Hey Fergeson-
Let's see if we can get you going in the right direction here. You
Are most of the way there since you have your parser and view
already. You need a database table, a model for that table and a
controller to get data from the view and stick it in the model.
So first you need to create a migration for the db table. Lets call
it localized_strings. So from inside of your rails app run this command:
$ script/generate model LocalizedString
That will create a file in RAILS_ROOT/db/migrate/
001_create_localized_strings.rb . Put this inside of it:
class CreateLocalizedStrings < ActiveRecord::Migration
def self.up
create_table : localized_strings do |t|
t.column :key, :string
t.column :value, :string
end
end
def self.down
drop_table : localized_strings
end
end
Save that file and run rake migrate. You will now have a model called
LocalizedString to hold your data in after you parse it.
Lets make the view even simpler for now and just deal with the file
upload
Importing Strings
<%= start_form_tag({:action => 'create'}, :multipart => true)%>
<p>
<b>Path: </b><br />
<%= file_field "localized_string", "data"%>
</p>
<p><%= submit_tag "Import"%></p>
<%= end_form_tag%>
Now you need a controller to handle the busy work.
class MyController < ActionController::Base
def create
table = { }
# params[: localized_string][:data] is a File or StringIO
object when its a file upload
params[: localized_string][:data].each_line do |line|
if line =~ /^ \s* " (.?) " \s = \s* " (.*?) "/x
table[ $1 ] = $2
end
end
# loop over key=>val pairs in table and create new model
records from each one
table.each do |key,val|
LocalizedString.create(:key => key, :value => val)
end
end
end
That should get you where you need to go.
Cheers-
-Ezra