Rails 动态生成表和Model

Posted by wxianfeng Sat, 01 Aug 2009 17:12:00 GMT

环境:ruby 1.9.2 + rails 3.0.3 + ubuntu 10.10

项目需要运行中动态生成表 和 Model , 怎么办 ?

借助 ActiveRecord::Migration 来实现 动态建表 和 字段

可以 借助 Object.const_set 来实现 动态Model

DEMO:

# RUN : rails runner lib/dynamic_table.rb

ActiveRecord::Migration.create_table :posts
ActiveRecord::Migration.add_column :posts, :title, :string

Object.const_set(:Post,Class.new(ActiveRecord::Base)) # => Object.class_eval { const_set(:Post,Class.new(ActiveRecord::Base)) }
# p Post.columns
p Post.column_names # ["id", "title"]

ActiveRecord::Migration.add_column :posts, :body, :text

p Post.column_names # ["id", "title"]

Object.class_eval { remove_const :Post }
Object.const_set(:Post,Class.new(ActiveRecord::Base))

p Post.column_names # ["id", "title", "body"]

动态Model 实质就相当于 Post = Class.new(ActiveRecord::Base) 或者 Post < ActiveRecord::Base

Class.new(ActiveRecord::Base) 参数指定 super_class , 默认是 Object

可以从ruby源码中看出:

  #     Class.new(super_class=Object)   =>    a_class
  #
  #
  # Creates a new anonymous (unnamed) class with the given superclass
  # (or <code>Object</code> if no parameter is given). You can give a
  # class a name by assigning the class object to a constant.
  #
  #
  #
  def self.new(super_class=Object)
    # This is just a stub for a builtin Ruby method.
    # See the top of this file for more info.
  end

当给表添加了新的字段后,Model 需要重新 const_set 一次 ,注意 const_set 之前 需要 remove_const 一次 , 不然会出现 已经初始化的警告

see:

http://hildolfur.wordpress.com/2006/10/29/class-reloading-in-ruby/

This entry was posted on Sat, 01 Aug 2009 17:12:00 GMT and Posted in , . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.

Tags ,


Trackbacks

Use the following link to trackback from your own site:
http://blog.wxianfeng.com/trackbacks?article_id=136

Comments

  1. Avatar
    Joey over 1 year ago:

    很高级阿
    动态的生成了migration之后 也要自动的migrate到DB么?

  2. Avatar
    poker Qq online over {{count}} years ago:

    I was recommended this website by means of my cousin. I’m no longer certain whether this submit is
    written by way of him as no one else realize such exact approximately
    my difficulty. You’re wonderful! Thank you!

  3. Avatar
    poker Qq online over {{count}} years ago:

    I was recommended this website by means of my cousin. I’m no longer certain whether this submit is written by way of him as no
    one else realize such exact approximately my difficulty.
    You’re wonderful! Thank you!

Leave a comment