Establish a connection to another database only in a block?

后端 未结 7 1141
情书的邮戳
情书的邮戳 2020-12-29 10:17

In a rails application, I have this code in pure ruby :

class LinkCreator
  attr_accessor :animal

  def initialize(animal:)
    @animal = animal
  end

  de         


        
7条回答
  •  庸人自扰
    2020-12-29 10:36

    It would be nice if you keep all database connections in database.yml

    development:
      adapter: mysql2
      other stuff...
      
    db_2:
      adapter: mysql2
      other stuff..
    
    other_envs:
    .....
    

    Then create a class

    class OtherDB < ActiveRecord::Base
      establish_connection(:db_2)
    end
    

    From your controller you can access just like

    OtherDB.table_name = "table_name"
    OtherDB.first
    

    Check my blog here http://imnithin.github.io/multiple-database.html

提交回复
热议问题