17

I want to execute this sql script inside my seed.rb

LOAD DATA LOCAL INFILE '/home/list-38.csv'
INTO TABLE list
FIELDS TERMINATED BY ':'
LINES TERMINATED BY '\n'
(email,name,password);

I checked this link but unable to figure out the solution.So that once we run rake db:seed

How to seed mysql database by running sql scripts in Ruby Rails platform? it dumps my data into the table.

any queries ..do reply

Thanx

4 Answers 4

33

Try this in db/seeds.rb to execute raw SQL with rake db:seed

connection = ActiveRecord::Base.connection()
connection.execute("*_YOUR_SQL_HERE_*")
1
  • 1
    Hello, Paul. What if I want to add a second sql query for another table, or even more tables? Should I add a new line? connection.execute("*_2nd_SQL_HERE_*") and comment the 1st line? May 22, 2013 at 9:38
7

For multiple sql statements, I ended up iterating over each statement separately:

# db/seeds.rb

connection = ActiveRecord::Base.connection()

sql = <<-EOL
  INSERT INTO users values ('Admin');
  INSERT INTO categories values ('Supervisors');
EOL

sql.split(';').each do |s|
  connection.execute(s.strip) unless s.strip.empty?
end
1
  • 1
    Great answer! Thank you for that. Helped me a lot!
    – coderuby
    Sep 14, 2016 at 18:22
4

A variation on Fredrik Boström's answer that can load from a file:

# db/seeds.rb

def execute_sql_file(path, connection = ActiveRecord::Base.connection)
  require 'active_support/core_ext/object/blank.rb'
  IO.read(path).split(';').reject(&:blank?).each do |statement|
    connection.execute(statement)
  end
end

execute_sql_file('my.sql')
1

Super late to this answer but hopefully it helps someone in my position. Instead of iterating over each sql statement you can use .execute_batch using a direct connection to your database with the database version you are using. Below is an example with SQLite3.

#db/seeds.rb

DB = {:conn => SQLite3::Database.new("./db/development.sqlite")}

sql = <<-EOL
  INSERT INTO users values ('Admin');
  INSERT INTO categories values ('Supervisors');
EOL

DB[:conn].execute_batch(sql)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.