2011-01-12 48 views
3

我有一個將根據日期動態創建表格的遷移。事情是這樣的:動態創建導軌中的表格模型

class CreateCollectorPeriodTable < ActiveRecord::Migration 

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

我希望創建一個將訪問此遷移模型..

我看過這樣的:Rails Generate Model from Existing Table?,但另一個問題有人解釋爲什麼我不應該嘗試做一個模型適合很多表格。

有什麼建議嗎?

+0

你能解釋一下這個背後的推理嗎?你想達到什麼目的? – nathanvda 2011-01-12 21:24:45

回答

4
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 
+0

哇,這是光滑的。非常感謝! – Tommy 2011-01-12 20:51:07