RoR + MySQL の環境へデータ投入 #2


新しいテーブルを追加する方法を試す。
id:satake7:20080518:p1 今までのようにdb/migrate/*_create_*.rbを直接編集しないやり方。


*.rbに書いていたフィールド定義をコマンドラインで直書きして実行。今回はb52というテーブルを追加することにする。

> ruby script/generate scaffold b52 name:string wmoid:integer idvid:string unqid:stringsrc:string lat:float lon:float alt:float
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/b52s
exists app/views/layouts/
exists test/functional/
exists test/unit/
exists public/stylesheets/
create app/views/b52s/index.html.erb
create app/views/b52s/show.html.erb
create app/views/b52s/new.html.erb
create app/views/b52s/edit.html.erb
create app/views/layouts/b52s.html.erb

identical public/stylesheets/scaffold.css
create app/controllers/b52s_controller.rb
create test/functional/b52s_controller_test.rb
create app/helpers/b52s_helper.rb

route map.resources :b52s
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/b52.rb
create test/unit/b52_test.rb
create test/fixtures/b52s.yml

exists db/migrate
create db/migrate/20090324032152_create_b52s.rb

出来たフィールド定義を確認する。more db/migrate/*_create_b52s.rb

class CreateB52s < ActiveRecord::Migration
def self.up
create_table :b52s do |t|
t.string :name
t.integer :wmoid
t.string :idvid
t.string :unqid
t.string :src
t.float :lat
t.float :lon
t.float :alt

t.timestamps
end
end

def self.down
drop_table :b52s
end
end

以前、自分で手書きで作成した内容と一緒だ。OK。ただし、unqidは :null => faulse にしたいのだけど、どうやって書けば良いのだろう。これは後で調べること。


テーブルを削除する。 rake db:migrate VERSION=0
テーブルを作る。 rake db:migrate 今までのb5sと、新たにb52sができる。
csvファイルを用意する。 test/fixtures/b52s.csv 同名のb52s.ymlは削除すること。これが残っているとrake db:fixtures:loadでymlが優先されてしまうらしい!
投入。 rake db:fixtures:load FIXTURES=b52s RAILS_ENV=development

MySQLのコマンドで中身を見ると、ちゃんと入っていることが分かる。やっと、やりたいことが出来た〜!

つまりは、前トピックのやり方で、test/fixtures/*.ymlを削除して実施すれば同じことができる、だろう。