解決:プラグインからDBのテーブルを作る方法

見つけました。というか独自にテーブルが必要そうなプラグインをインストールして,どうやっているかを見てみました。とりあえず以下のコードで動くことを確認。

class TestDB
  def createtable
    ActiveRecord::Schema.create_table('test'do |t|
      t.column :str, :string
    end
  end
end

これをlibディレクトリにtest_db.rbとして保存し,コンソールを開いて a = TestDB.new と a.createtable を実行したらテーブルができました。実際にはテーブルの存在チェックなどが必要ですが,ともかくこれでプラグイン内でテーブルが作れることが分かりました。

ActiveRecord::Schemaのドキュメントを見ると
  ActiveRecord::Schema.define do
    create_table :authors do |t|
      t.string :name, :null => false
    end

    add_index :authors, :name, :unique

    create_table :posts do |t|
      t.integer :author_id, :null => false
      t.string :subject
      t.text :body
      t.boolean :private, :default => false
    end

    add_index :posts, :author_id
  end

といった書き方ができるようです。

プラグイン・オプションも含めてプラグイン内マイグレーション機能を入れたら結構使いやすいのではないかといったことを考えています。


« Prev item - Next Item »
---------------------------------------------

Comments


No comments yet. You can be the first!


Leave comment

© 2007 yoursite.com | Designed by DesignsByDarren
Ported to Nucleus CMS: Suvoroff