为 rails 中的表格动态创建模型 [英] Dynamically creating models for a table in rails

查看:48
本文介绍了为 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..

我确实读过这个:Rails 从现有表生成模型?,但在另一个问题中,有人解释了为什么我不应该尝试让一个模型适合多张桌子..

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..

有什么建议吗?

推荐答案

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

这篇关于为 rails 中的表格动态创建模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆