title: How to configure ActiveRecord connection in gem and parent app?
body: <p>Short version: </p>
  
  <p>How to provide separate configurations to ActiveRecord in rails app and gem (living in the same source code) based on same <code>config/database.yml</code>. The configurations differ only in <code>schema_search_path</code> value</p>
  
  <p>Long version:</p>
  
  <p>I have a rails application (<em>parent</em>) and I'm extracting part of it into a gem (<em>child</em>). The child app is just a gem with its own models. Not a rails engine or mountable rails engine. Its models would live in the same Postgres database but in a separate schema. E.g. <em>parent</em> app models are in <code>public</code> schema and <em>child</em> app models are in <code>child</code> schema.</p>
  
  <blockquote>
    <p>As a sidenote I'm managing migrations using <code>standalone-migrations</code> gem and running migrations separately on <em>parent</em> and <em>child</em> so <em>child</em> gets its own <code>schema_migrations</code> table in its schema</p>
  </blockquote>
  
  <p>Rails allows the DB configuration to include <code>schema_search_path</code> so that's what I planned to use to provide the two configurations.</p>
  
  <p>I would like to avoid copying the <code>config/database.yml</code> to the <em>child</em> gem because the file would be 100% same except the <code>schema_search_path</code> for each environment.</p>
  
  <p>My idea (that is not working) was to use <em>railtie</em> initializer callbacks in the <em>child</em> gem to set the <code>Child::ApplicationRecord.configurations = conf_with_the_correct_schema_search_path</code> </p>
  
  <p>Using this approach, the <em>child</em> models (e.g. accessed using <code>Child::Name.all</code>) work but the manually added configuration (in railtie) gets used for the <em>parent</em> app too. Since the only schema in the <code>schema_search_path</code> is <code>child</code>, none of the parent models will be found.</p>
  
  <p>When assigning the configurations manually in rails console, I'm able to access both application's models UNTIL I do <code>ModelBaseClass.establish_connection</code> which will use the latest config and make either <em>parent</em> or <em>child</em> models unreachable. E.g. </p>
  
  <ul>
  <li>in <em>parent</em>: <code>ApplicationRecord.configurations = YAML.load(...)</code></li>
  <li>in <em>child</em>: create based on parent config</li>
  </ul>
  
  <p>Child config example:</p>
  
  <pre><code>add_child_schema_lookup = -&gt;(acc, keyval) do
    k, v = keyval
    acc.merge({k =&gt; v.merge(schema_search_path: 'child')})
  end
  child_configs = ApplicationRecord.configurations.reduce({}, &amp;add_child_schema_lookup) 
  Child::ApplicationRecord.configurations = child_configs
  </code></pre>