Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@kjakub kjakub commented Jan 30, 2014

Very helpful!

@hnishide

This comment has been minimized.

Copy link

@hnishide hnishide commented Mar 7, 2014

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

@bipashant

This comment has been minimized.

Copy link

@bipashant bipashant commented Feb 3, 2015

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

@matDobek

This comment has been minimized.

Copy link

@matDobek matDobek commented May 30, 2016

\o/

@jo-tilkee

This comment has been minimized.

Copy link

@jo-tilkee jo-tilkee commented Jul 27, 2016

Thanks! Very helpfull ;-)

@fmarchena

This comment has been minimized.

Copy link

@fmarchena fmarchena commented Mar 12, 2017

Thanks! , excellent

@CodyFitzpatrick

This comment has been minimized.

Copy link

@CodyFitzpatrick 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

This comment has been minimized.

Copy link

@davidjeddy davidjeddy commented Jun 5, 2019

Very helpful. Thank you @seyhunak.

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