Tommy
Tommy

Reputation: 1819

Dynamically creating models for a table in rails

I have a migration that will dynamically create tables on fly per date. Something like this:

class CreateCollectorPeriodTable < ActiveRecord::Migration

  def self.create_with(name)  
    create_table name.to_sym do |t|
      t.string :text, :limit => 1024
    end
  end 
end

I want to create a model that will access this migration..

I did read this: Rails Generate Model from Existing Table?, but in another question someone explained why I shouldn't try and make one model fit many tables..

Any suggestions?

Upvotes: 2

Views: 3142

Answers (1)

fl00r
fl00r

Reputation: 83680

class CreateCollectorPeriodTable < ActiveRecord::Migration
  # name should be plural
  # i.e.: name = 'chickens'
  def self.create_with(name)  
    create_table name.to_sym do |t|
      t.string :text, :limit => 1024
    end
    model_file = File.join("app", "models", name.singularize+".rb")
    model_name = name.singularize.capitalize
    File.open(model_file, "w+") do |f|
      f << "class #{model_name} < ActiveRecord::Base\nend"
    end
  end 
end

Upvotes: 3

Related Questions