Skip to content

Instantly share code, notes, and snippets.

@seyhunak
Created December 7, 2013 14:54
Show Gist options
  • Save seyhunak/7843549 to your computer and use it in GitHub Desktop.
Save seyhunak/7843549 to your computer and use it in GitHub Desktop.
Rails - Import SQL file as seed
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
@kjakub
Copy link

kjakub commented Jan 30, 2014

Very helpful!

@hnishide
Copy link

hnishide commented Mar 7, 2014

The last statement would be removed unless the sql file had line break at the end of file.

@bipashant
Copy link

Thank you so much 😄
You saved me
You are the best

@matDobek
Copy link

\o/

@jo-tilkee
Copy link

Thanks! Very helpfull ;-)

@fmarchena
Copy link

Thanks! , excellent

@CodyFitzpatrick
Copy link

CodyFitzpatrick commented Jan 30, 2019

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 the TRUNCATE 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

@davidjeddy
Copy link

Very helpful. Thank you @seyhunak.

@marviorocha
Copy link

Very helpful, Thank you, @seyhunak

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment