今回はseeds.rbを使って初期データを放り込む方法について調べてみました。
まずは、modleを生成、必要なフォルダを作成します。
rails g model measure time:timestamp device_id:integer value:integer rake db:migrate mkdir -p db/seeds/development
つぎに、各種ファイルを生成します。
### #{Rails.root}/db/seeds.rb ### seedデータをどこから読み出すか指定します # -*- coding: utf-8 -*- # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) table_names = %w(measures) table_names.each do |table_name| path = "#{Rails.root}/db/seeds/#{Rails.env}/#{table_name}.rb" require(path) if File.exist?(path) end
### #{Rails.root}/db/seeds/development/measures.rb ##計測データのサンプルを生成します。 # -*- coding: utf-8 -*- ## rails g model data time:timestamp device_id:integer value:integer hours = 3 10.times do |device| (hours * 60).times do |i| Measures.create(:time => (Time.local(2013,3,1,0,0,0) + (i * 60)), #一分毎 :device_id => device , :value => rand(20) ) end # i end # device
ファイルの生成が終わったら、rakeにてseedファイルの生成を行います。
seeds,rbを変更した場合は、最後のresetだけやれば良いです。
rake db:seed rake db:reset
あとは、データベースが正常に格納されているか確認します。
$ sqlite3 db/development.sqlite3 SQLite version 3.7.7 2011-06-25 16:35:41 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> .mode column sqlite> select * from measures; 1 2013-02-28 15:00:00.000000 0 4 2013-03-25 13:47:08.117492 2013-03-25 13:47:08.117492 2 2013-02-28 15:01:00.000000 0 6 2013-03-25 13:47:08.125763 2013-03-25 13:47:08.125763 3 2013-02-28 15:02:00.000000 0 1 2013-03-25 13:47:08.129361 2013-03-25 13:47:08.129361 4 2013-02-28 15:03:00.000000 0 14 2013-03-25 13:47:08.132659 2013-03-25 13:47:08.132659 . . . 1799 2013-02-28 17:58:00.000000 9 9 2013-03-25 13:47:12.387484 2013-03-25 13:47:12.387484 1800 2013-02-28 17:59:00.000000 9 13 2013-03-25 13:47:12.389726 2013-03-25 13:47:12.389726