Monday, November 14, 2011

How to add your json file to you sqlite database, aka seed your db

If you are using rails and have data in json format that you want to add to your database you want to use the ‘rake db:seed’ task to do this. So lets say my json data looks like this:

{“idnumber”: “00xx76”,”username”: “suiuk”,”firstname”: “Rue”,”lastname”: “Ouk”,”email”: “”,”phonenumber”: “333-555-1921 ext 191”,”isactive”: true ,”lastfour”: “7001” }, {“idnumber”: “00xx552”,”username”: “ronyne”,”firstname”: “Rond”,”lastname”: “Lne”,”email”: “”,”phonenumber”: “444-555-1921 ext 334”,”isactive”: true ,”lastfour”: “3668” }

Here is what my db/seeds.rb file will look like…

json = ActiveSupport::JSON.decode(‘db/tests.json’)) json.each do |a| Test.create!(:idnumber => a‘idnumber’], :username => a‘username’, :firstname => a‘firstname’], :lastname => a‘lastname’], :email => a‘email’, :phonenumber => a‘phonenumber’], :isactive => a‘isactive’], :lastfour => a‘lastfour’],) end

..and for good measure here is the what the db schema looks like…

sqlite> .schema tests CREATE TABLE tests(idnumber integer, username string, firstname string, lastname string, email string, phonenumber string, isactive boolean, lastfour string);

Now to run this do ‘rake db:seed’ Also, be sure you have a model (app/model/yourstuff.rb) that accompanies the table in the database. I was playing around with this in the beginning and I kept getting the error ‘Uninitialized Constant’ until I created the model code.

No comments:

Post a Comment