Multiple DB connection in rails

前端 未结 3 1358
遇见更好的自我
遇见更好的自我 2021-02-10 06:43

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:17

    Thanks for reply.

    we can migrate a model for particular DB, for example

    db:migrate RAILS_ENV="portal_development"'.

    And more change for establishing connection with DB.check the corrected below

    class Test1Base < ActiveRecord::Base
      self.abstract_class = true
      establish_connection :development
    end
    
    class Test2Base < ActiveRecord::Base
      # No corresponding table in the DB.
      self.abstract_class = true
      establish_connection :portal_development
    end
    

    Thanks sameera for your valuable reply.

    cheers

    Shamith c

    0 讨论(0)
  • 2021-02-10 07:19

    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
    
    0 讨论(0)
  • 2021-02-10 07:21

    Possibly use active_delegate? http://railslodge.com/plugins/595-active-delegate

    0 讨论(0)
提交回复
热议问题