Mysql – How to seed thesql database by running sql scripts in Ruby Rails platform

databaseMySQLrubyruby-on-rails

I have been basically java programmer and beginner for Ruby Rails. In java, to seed database ant task is run, the ant task execute SQL script. SQL script is basically set of insert statements.

I expect there must be some equivalent of ant task on Ruby Rails platform for running sql script?

Edited in response to answer by Nikita:

Although one can use Migration as one of way for seeding data. But I don't want to do rework of writing migration classes corresponding to sql scripts. so i need some solution through which i have to exec sql script file only. I want to manage by database only through sql code.

Best Answer

I personally don't like using migrations to seed large amounts of "static" data. You can easily execute sql statements from db/seeds.rb by:

# Empty the soon-to-be-seeded table
MyModel.delete_all

# Get the current DB connection
connection = ActiveRecord::Base.connection();

# Execute a sql statement
connection.execute("Insert INTO my_models (id, name) VALUES
    (1, 'Example 1'),
    (2, 'Example 2'),
    (3, 'Example 3');")

Basically, once you have the current connection, you can just call a sql statement useing connection.execute("SQL CODE HERE").