create dynamic model and store the values to table

Hi,

I have a CSV upload option and need to create a table and model based on the CSV colums.

We allow to upload different kind of CSV file formats and each file upload will create new table and info will be stored accordingly. I have created a table with columns based on CSV file header and also created a model base on CSV file name. But when i store the file details to specific table i faced error.

def self.import(file, head, csvalue,fname)

ActiveRecord::Schema.define do

create_table “#{fname}” do |t|

#(define your columns just as you would in a migration file)

head.each do |h|

t.text h

end

t.string :my_string

end

end

model_file = File.join(“app”, “models”, fname.singularize+".rb")

model_name = fname.singularize.capitalize

File.open(model_file, “w+”) do |f|

f << “class #{model_name} < ActiveRecord::Base\nend”

end

ss=model_name.new

p ss=model_name.constantize.new

file="#{fname}_#{cnt}"

return file

end

How can declare the object for dynamic model. Because I couldn’t store the values to new table.

I faced the Error like NameError (uninitialized constant Mytest):

Any idea how to solve this ?

I do not know if this will work, but you probably need to manually require the model file you create before you try to constantize the model name. I don’t think Rails autoloading is working in this situation.

Hi Tamosus pontik,

Thanks for your reply.

The model file is created dynamically based on this code.

model_file = File.join(“app”, “models”, fname.singularize+".rb")

model_name = fname.singularize.capitalize

File.open(model_file, “w+”) do |f|

f << “class #{model_name} < ActiveRecord::Base\nend”

end

But i need to store the values to specific tables.

Note: I am not running migration for the dynamic tables(model)

Hi Tamosus pontik,

Thanks for your reply.

The model file is created dynamically based on this code.

And after you write that file, you need to require it for Rails to use it. That’s why the constant is undefined.

Do you know how the require statement works in Ruby?

Thank you Tamosus pontik.

I have done the task using this keyword require “#{dynamic_model_name}”

Hi Daynthan,

I have the same problem. So I see you got working solution.

Please, can you post final version of working important files?

Thank you.

vocabularies = File.read(Rails.root.join('lib', 'seeds', 'words.csv'))
csv = CSV.parse(vocabularies, :headers => true, :encoding => 'ISO-8859-1')
csv.each do |row|
  t = Vocabulary.new
  t.word_column1 = row[0]
  t.word_column2 = row[1]
  t.word_column3 = row[2]
  t.word_column4 = row[3]
  t.word_column5 = row[4]
  t.save!
  puts "#{t.word_column1}, #{t.word_column2} saved"
end

This is for your seed file. You can create a task for it as well.

Thank you David