Multiple DB connection in rails

前端 未结 3 843
生来不讨喜
生来不讨喜 2021-02-10 06:45

I am trying to connect multiple database in ROR application.My database.yml is look like this in your database.yml file

development:

 adapter: mysql
 us         


        
3条回答
  •  无人及你
    2021-02-10 07:22

    Try

    rake db:create:all
    

    And yes, it's possible to have multiple db connections in a Rails application.

    This is what I did once, I have created two classes which inherit from ActiveRecord::Base and set the connections inside those classes.

    Then I inherited all my models in one of those classes instead of direct ActiveRecord

    Below is an example:

    database.yml file
    
    #app uses two database
    #1 - test1
    #2 - test2
    test1:
      adapter: mysql
      encoding: utf8
      database: test1
      username: root 
      password: xxx
      host: localhost
    
    test2:
      adapter: mysql
      encoding: utf8
      database: test2
      username: root
      password: xxx
      host: localhost
    

    Then I have two models for both test1 and test2 databases:

    class Test1Base < ActiveRecord::Base
        self.abstract_class = true
        establish_connection("test1")
    end
    
    class Test2Base < ActiveRecord::Base
      # No corresponding table in the DB.
      self.abstract_class = true
      establish_connection("test2")
    end
    

    Then I inherit my models according to database:

    class School < Test1Base
      #code
    end
    
    class Student < Test2Base
      #code
    end
    

提交回复
热议问题