Created
December 7, 2013 14:54
-
-
Save seyhunak/7843549 to your computer and use it in GitHub Desktop.
Rails - Import SQL file as seed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unless Rails.env.production? | |
connection = ActiveRecord::Base.connection | |
connection.tables.each do |table| | |
connection.execute("TRUNCATE #{table}") unless table == "schema_migrations" | |
end | |
sql = File.read('db/import.sql') | |
statements = sql.split(/;$/) | |
statements.pop | |
ActiveRecord::Base.transaction do | |
statements.each do |statement| | |
connection.execute(statement) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just so everyone that may stumble on this page from Google (as I did) fully understands, this script will empty out your tables before seeding it with data from
db/import.sql
. This is due to theTRUNCATE
SQL command on line 4. If you have seeded your database tables with other data prior to running this, you will lose that data.If you are wanting to import data via SQL from within your
db/seeds.rb
file and you are running the standard rake command sequence to destroy then re-create and populate your database (rake db:drop db:create db:migrate db:seed
), change the script to this: Ruby on Rails - Import Data via SQL in seeds.rb