Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A good way to do that is making a model for each database connection you need, and then make other models as subclasses of them. So, for example:</p> <ol> <li>Define all the needed connections in database.yml (per-environment)</li> </ol> <pre class="lang-none prettyprint-override"><code> # DB 1 development: adapter: mysql2 encoding: utf8 database: db_1 username: **** password: **** host: ******** pool: 5 ... # DB 2 db2_development: adapter: mysql2 encoding: utf8 database: db_2 username: **** password: **** host: ******** pool: 5 ... # Same for production (and/or other environments) production: ... db2_production: ... </code></pre> <ol> <li>Define a "master" model for each database, which inherits from <code>ActiveRecord::Base</code></li> </ol> <pre class="lang-rb prettyprint-override"><code> # DB1 class DB1 &lt; ActiveRecord::Base self.abstract_class = true end # DB2 class DB2 &lt; ActiveRecord::Base self.abstract_class = true establish_connection "db2_#{Rails.env}" end ... </code></pre> <ol> <li>Now define all the database-specific models as subclasses of the models defined above, in this way:</li> </ol> <pre class="lang-rb prettyprint-override"><code> # DB1 specific model class DB1_model &lt; DB1 # model logic here end # DB2 specific model class DB2_model &lt; DB2 # model logic here end ... </code></pre> <p>And you're good to go.</p> <p>In this way, you can connect to N databases in different environments (usually <code>development</code>, <code>staging</code>, <code>preprod</code> and <code>production</code>, but they may be different in your case).</p> <p>Also, remeber that Rails will manage a pool of SQL connections for each database. </p> <p>In the example above, Rails will open a maximum of <strong>5 connections</strong> for each database, so total will be <strong>10</strong> (for a <strong>single instance of your application</strong>). If you use Phusion Passenger or Unicorn, and spawn 8 application instances, total SQL connections will be (at maximum) 10*8 = 80.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload