1

In my Rails application development, I would like to write a script to create a new database and a table in the new database (I am using MySQL), so that I can later run the script like following:

rails runner db/scripts/data_mover.rb

But I do not know how to do it in ruby code or Rails way...Anyone can provide some hint or sample?

2
  • Just do what you do in migration Commented Nov 24, 2011 at 11:53
  • How? I need to create a new database, not only table Commented Nov 24, 2011 at 12:05

1 Answer 1

2

write the code in a class, and place the file under app/models, such as `app/models/data_mover.rb'

class DataMover
  def self.run
    ActiveRecord::Base.connection.execute("CREATE DATABASE somedatabase")

    ActiveRecord::Base.establish_connection(
     :adapter  => "mysql",
     :host     => "localhost",
     :username => "myuser",
     :password => "mypass",
     :database => "somedatabase"
    )

    ActiveRecord::Base.connection.create_table :sometable do |t|
      #...
    end
  end
end

Then you can run rails runner 'DataMover.run' to create databases and tables.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.