Reputation: 15765
How can I extract the data in the rails sqlite3 db to a file?
I'm using rails 4.
I would like to extract all the data in my database so I can reload it later when I reset my database, or when I switch to a different type of db.
Upvotes: 9
Views: 4410
Reputation:
Use "yaml_db" gem. https://github.com/ludicast/yaml_db
rake db:data:dump
to dump data (Data is stored in a seperate file after dumping) and
rake db:data:load
to load data to other database
Upvotes: 5
Reputation: 10251
You can simple write this line in seeds.rb
File.open("post.json", "w") { |f| f.write Post.all.to_json }
here Post
should be replaced with your model's name.
then run in terminal:
rake db:seed
Upvotes: 3
Reputation: 81
i used to extract all db to json using userfriendly phpmyadmin export. it create easily export json data for your database. hope this will help you.
goto phpmyadmin
export / type json
Upvotes: 0
Reputation: 6357
I totally agree with .dump
instead of generating a json dump. But only for curiosity I wrote a script to convert all models into json.
Rails.application.eager_load! # To load all models app/models/**/*.rb
all_records = ActiveRecord::Base.descendants.map &:all
all_records.to_json
But it probably will take so long to perform in a real environment with many records.
Another way (which I recommend for this case) as the Sqlite3 is only a file, just copy the file db/development.sqlite3
to db/development.sqlite3.backup
. When you want to recover it, just copy it back cp -f db/development.sqlite3.backup db/development.sqlite3
. Remember that the .dump
generates an ASCII text file with the inserts and creates statements, you can't recover it in the database which it was extracted, because it will attempt to duplicate the records.
Upvotes: 3
Reputation: 13014
Simply create a DB dump file of your database and use it when you want.
Assuming you want to dump the database for db/development.sqlite3
,
this is straight from the Sqlite3 Help:
Use the "
.dump
" command to convert the entire contents of a database into a single ASCII text file. This file can be converted back into a database by piping it back into sqlite3.
To create the dump file:
echo '.dump' | sqlite3 db/development.sqlite3 | gzip -c > dev.dump.gz
To restore the dump file:
zcat dev.dump.gz | sqlite3 development.sqlite3
Upvotes: 2