Dynamically create models for a table in rails

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

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 read the following: Rails Generate Model from an existing table? , but in another question, someone explained why I should not try and that one model matches many tables ..

Any suggestions?

+3
source share
1 answer
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
+4
source

Source: https://habr.com/ru/post/1785057/


All Articles