2011-01-12 6 views
3

필자는 날마다 테이블을 동적으로 생성하는 마이그레이션 작업을 수행하고 있습니다. 이런 식으로 뭔가 : Rails Generate Model from Existing Table?,하지만 난 시도하고 일을하지 말아야하는 이유 다른 질문에서 누군가가 설명 :이 읽었다레일로 테이블의 모델을 동적으로 생성하기

나는이 마이그레이션에 액세스 할 모델을 만들

class CreateCollectorPeriodTable < ActiveRecord::Migration 

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

.. 모델에 맞는 많은 테이블 ..

어떤 제안?

+0

이 문제에 대한 추론을 좀 더 설명해 주시겠습니까? 무엇을 성취하려고합니까? – nathanvda

답변

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

+1

이것은 효과가 있습니다. 그것만이'rails g model text : string'과 거의 동일하게 보입니다. 그래서 유즈 케이스가 무엇인지 모르겠습니다. – nathanvda

+0

@nathanvda, 절대적으로 :) 그것은 나를 위해 아주 이상한 과제입니다. – fl00r

관련 문제