Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute sql script inside seed.rb in rails3

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

like image 952
Bijendra Avatar asked Jun 03 '11 06:06

Bijendra


2 Answers

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

connection = ActiveRecord::Base.connection()
connection.execute("*_YOUR_SQL_HERE_*")
like image 136
Paul Groves Avatar answered Sep 22 '22 02:09

Paul Groves


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
like image 39
Fredrik Boström Avatar answered Sep 20 '22 02:09

Fredrik Boström