Trey Copeland
Trey Copeland

Reputation: 3527

How to create rails migration with data?

I'm working on creating a simple rails application with artist and lyrics. I have a mysql database with two tables called Artists and Lyrics that already contains data. What type of migrations do I create to use this data? What steps do I take next after creating my new rails project?

My database structure looks like:

Artists
-------
| ArtistID | SongID | ArtistName |


Lyrics
-------
| SongID | SongName | Lyrics |

I would greatly appreciate any help and thanks for your time.

Upvotes: 1

Views: 1125

Answers (2)

Aleks
Aleks

Reputation: 5388

You can do that by following the next steps:

  1. Create config/database.yml to reference your database and fill in all the necessary information
  2. Run rake db:schema:dump in console to generate db/schema.rb, like this:

    $ rake -T db:schema:dump

    (or without -T)

  3. Create a blank migration file, or generate a new one with:

    $ rails g migration CreateNewRailsTables

  4. Then open the newly created file located in db/migrations/20160317_create_new_rails_tables.rb

And paste this code (replace the comments with the actual data):

class CreateNewRailsTables < ActiveRecord::Migration
  def self.up
    # Open schema.rb and copy-paste content of it here
  end

  def self.down
    # Leave it blank
  end
end

Upvotes: 1

Matouš Bor&#225;k
Matouš Bor&#225;k

Reputation: 15954

I think you don't have to do anything special to incorporate an existing database to your rails project. If you already have the tables with data, add only the appropriate model classes and run rake db:schema:dump once to create the schema.rb file. Of course I assume you have a correct configuration set up in config/database.yml.

See this blog post for more detailed info.

Upvotes: 0

Related Questions