'Connect' a rails app to an already existing MySQL DB?

前端 未结 3 1250
执念已碎
执念已碎 2021-01-07 12:42

So in my company we are slowly moving to Rails instead of PHP(Code Igniter to be precise). So, our actual PHP App is using a Mysql DB and I\'d like to connect a new Rails ap

3条回答
  •  没有蜡笔的小新
    2021-01-07 13:18

    There are two aspects of a Rails app to consider for this scenario:

    1: the database connection

    Simply put the credentials for this database into database.yml.

    A model like "User" will by default attempt to find records and attribute definitions in a table called "users". ActiveRecord will assume there's an auto-incrementing integer primary key on each table. When saving records, it will attempt to write to columns called created_at and updated_at. Those are a few things to be mindful of when making and using the connection.

    2: the database migrations

    Rails uses migration files to manage a sequence of changes to the database structure. Under normal conditions, someone building a Rails app will be starting with an empty database.

    In the case of an existing database, I would recommend making a migration something like:

    class BuildLegacyDbStructure < ActiveRecord::Migration  
      def up
        Mysql2.connection.execute_some_sql_file(  # made-up function
          Rails.root.join('path', 'to', 'file')
        )  
      end
    
      def down
        # reverse those changes; bring DB down to blank state
      end
    end  
    

    Another option would be to disable Rails/ActiveRecord's migration-based management of the database entirely. For example Rails will generate a migration when you generate a new model. So if you have an existing users table in your PHP app, and you'd like to make a rails model to use this table, you'd run something like rails generate model User --no-migration.

提交回复
热议问题