- require 'tenarai/db'
- require 'tenarai/db/container'
- # DB へ格納するオブジェクトのクラス定義
- class Entry < Tenarai::DB::Row
- column Tenarai::DB::String.new('title', :length => 255)
- column Tenarai::DB::String.new('body')
- column Tenarai::DB::Date.new('created')
- column Tenarai::DB::Reference.new('comment', :multiple => true)
- column Tenarai::DB::Reference.new('tag', :multiple => true)
- end
- class Comment < Tenarai::DB::Row
- column Tenarai::DB::String.new('body')
- column Tenarai::DB::Reference.new('entry')
- end
- class Tag < Tenarai::DB::Row
- column Tenarai::DB::String.new('name')
- column Tenarai::DB::Reference.new('entry', :multiple => true)
- end
- # DB への接続
- Tenarai::DB.new(
- :engine => 'mysql',
- :db => 'test',
- :user => 'db_user',
- :password => 'db_password'
- ) do |db|
- table = Tenarai::DB::Container.new(
- db,
- # テーブル名と格納するオブジェクトのクラス名などを設定
- :table => [
- # 'テーブル名' => {:row => 'Row クラス名', :table => 'Table クラス名'}
- 'entry' => {:row => 'Entry' },
- 'comment' => {:row => 'Comment'},
- 'tag' => {:row => 'Tag' }
- ]
- # テーブル間のリレーションを設定
- :relation => [
- # ['テーブル名.カラム名', 'テーブル名.カラム名']
- ['entry.comment', 'comment.entry'],
- ['entry.tag', 'tag.entry' ]
- ]
- )
- # 全てのテーブルとリレーションをデータベースに作成
- # (create table や alter table ... add foreign key など)
- table.create
- # オブジェクトの作成とデータベースへの格納
- tag_climbing = Tag.new(tabl['tag'])
- tag_climbing.name = '山登り'
- tag_climbing.save
- tag_mt_iwate = Tag.new(tabl['tag'])
- tag_mt_iwate.name = '岩手山'
- tag_mt_iwate.save
- tag_mt_hayachine = Tag.new(tabl['tag'])
- tag_mt_hayachine.name = '早池峰山'
- tag_mt_hayachine.save
- entry1 = Entry.new(table['entry'])
- entry1.title = '岩手山に登ってきました'
- entry1.body = '頂上でお鉢めぐりです。頂上の地面が一部温かい。煙モクモク。さすが火山だけある。'
- entry1.created = Time.now
- entry1.save
- # リレーションの作成と保存
- entry1.tag << tag_climbing
- entry1.tag << tag_mt_iwate
- entry1.save
- tag_climbing.save
- tag_mt_iawte.save
- # オブジェクトの作成とデータベースへの格納
- entry2 = Entry.new(table['entry'])
- entry2.title = '早池峰山に登ってみたい'
- entry2.body = '実はまだ登ってません。岩場がゴロゴロしたところを登るらしい。実は子供のころに登っていたらしい?記憶なし。'
- entry2.created = Time.now
- entry2.save
- # リレーションの作成と保存
- tag_climbing.entry << entry2
- tag_mt_hayachine.entry << entry2
- tag_climbing.save
- tag_mt_hayachine.save
- entry2.save
- # オブジェクトの作成とデータベースへの格納
- comment1 = Comment.new(table['comment'])
- comment1.body = '御神坂から登って網張から下ったんだって?'
- comment1.save
- comment2 = Comment.new(table['comment'])
- comment2.body = '網張温泉の露天風呂はハエたたきでアブをバチンバチン。やるか、やられるか... 楽しいw'
- comment2.save
- # リレーションの作成と保存
- entry1.comment << comment1
- entry1.save
- comment1.save
- comment2.entry = entry1
- comment2.save
- entry1.save
- # 全てのテーブルとリレーションをデータベースから削除
- # (drop table や alter table ... drop foreign key など)
- table.drop
- end
[PageInfo]
LastUpdate: 2008-05-12 21:43:34, ModifiedBy: junkikuchi
[Permissions]
view:all, edit:members, delete/config:members