LoginSignup
23
22

More than 5 years have passed since last update.

Railsでjsonファイルのデータをdbに入れる

Last updated at Posted at 2015-05-27

はじめに

railsでwebアプリを作るにあたって利用したいjsonデータがある。
これをdbにどかんと入れたい。

db>seeds.rbを使う

dbフォルダ直下にあるseeds.rbは、railsアプリのデータベースにデータを投入するやつ。

$ rake db:seed

のコマンドでデータを投入することができる。
例えば、hogeモデル(hogesテーブル)に新しいレコードを入れる時は、
seeds.rbに、

db>seeds.rb
Hoge.create( column1:"セル1", column2:"セル2", column3:"セル3")

と書いてやる。

そして、

$ rake db:seed

してやるならば、

$ rails dbconsole 
SQLite version 3.7.13 2012-07-17 17:46:21
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>.tables
hoges              schema_migrations
sqlite>select * from hoges;
1|セル1|セル2|セル3|2015-05-24 04:03:24.555191|2015-05-24 04:03:24.555191

となる。
入った。

seeds.rbを使って、jsonファイルから一気に読み込む

あとは、seeds.rbをうまいように書けばいいだけ。
投入するjsonファイルはこんな感じ。

hoge.json
[
{"key1":"value1-1", "key2":"value2", "key3":"value3", "key4":"value4",},
{"key2":"value2-1", "key2":"value2-2", "key3":"value2-3", "key4":"value2-4",},
....
]

ここから、key1とkey4の値を取り出して、dbのhogesテーブルに投入するためのseeds.rbは、

db>seeds.rb
# ActiveSupport::JSONを使ってhoge.jsonをデコードしてrubyオブジェクトに変換。変数jsonに展開
json = ActiveSupport::JSON.decode(File.read('hoge.json'))

# 変数jsonに入った配列状態のjsonデータを一つ一つ取り出して、モデル.createを使ってdbに投入
json.each do |data|
  Hoge.create(column1:data['key1'], column2:data['key4'])
end

こんな感じ。

すると、dbのhogesテーブルはこうなる。

$ rails dbconsole 
SQLite version 3.7.13 2012-07-17 17:46:21
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>.tables
hoges              schema_migrations
sqlite>select * from hoges;
1|value1-1|value1-4|2015-05-24 04:03:24.555191|2015-05-24 04:03:24.555191
2|value2-1|value2-4|2015-05-24 04:03:24.555191|2015-05-24 04:03:24.555191
3|value3-1|value3-4|2015-05-24 04:03:24.555191|2015-05-24 04:03:24.555191
...
n|valuen-1|valuen-4|2015-05-24 04:03:24.555191|2015-05-24 04:03:24.555191

たくさん入っている。

おわりに

これで、大量のデータも投入することができるようになりました。

参考

https://gist.github.com/shvetsovdm/6317604
http://www.rubylife.jp/rails/model/index10.html
http://railsdoc.eiel.info/active_support/json/

23
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
22